<?php
namespace Seller\Controller;
require_once './ThinkPHP/Library/Vendor/yiwei/autoload.php';
use BarcodeBakery\Common\BCGColor;
use BarcodeBakery\Common\BCGDrawing;
use BarcodeBakery\Common\BCGFontFile;
use BarcodeBakery\Barcode\BCGcode128;

use Seller\Logic\OrderLogic;
use Think\AjaxPage;
use Think\Log;
use Think\Page;
vendor('grafika.autoloader');
use Grafika\Color;
use Grafika\Grafika;
use Grafika\GrafikaHelper; 
use Grafika\Curl;

class OrderController extends BaseController {
    public  $order_status;
    public  $shipping_status;
    public  $pay_status;
    /*
     * 初始化操作  
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        // 订单 支付 发货状态
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        $this->assign('order_status',$this->order_status);
        $this->assign('pay_status',$this->pay_status);
        $this->assign('shipping_status',$this->shipping_status);
    }

    /*
     *订单首页
     */
    public function index(){
    	$begin = date('Y-m-d 00:00:00',(time()-30*60*60*24));//30天前
    	$end = date('Y-m-d 23:59:59',strtotime('+1 days')); 	
    	$this->assign('timegap',$begin.' - '.$end);
        $this->display();
    }
    /*
     *Ajax首页
     */
    public function ajaxindex(){
        $orderLogic = new OrderLogic();
        $timegap = I('timegap');
        if($timegap){
        	$gap = explode(' - ', $timegap);
        	$begin = strtotime($gap[0]);
        	$end = strtotime($gap[1]);
        }
        // 搜索条件 STORE_ID
        $condition = array('a.store_id'=>STORE_ID); // 商家id
		I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") OR (a.mobile like "%'.I('consignee').'%")';
		I('goods_name') ? $condition['goods_name'] = array('like','%'.trim(I('goods_name')).'%'): false;
        if($begin && $end){
         	$condition['add_time'] = array('between',"$begin,$end");
        	
        // 	$condition['_string'] = 'add_time >='.$begin.' and add_time<='.$end;
        }
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        //I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
		if(I('order_status') == '3'){
			$condition['order_status'] = array('in','3,5');
		}elseif(I('order_status') == '4'){
		    $condition['order_status'] = 0;
		    $condition['shipping_status'] = 0;
		    $condition['stock_up'] = 2;
		}elseif(I('order_status') == '0'){
		    $condition['order_status'] = 0;
		    $condition['shipping_status'] = 0;
		    $condition['stock_up'] = 1;
		}elseif(I('order_status') != ''){
			$condition['order_status'] = I('order_status');
		}
		if(I('order_status') == 99){
		    $condition['order_status'] = array('not in','3,5');
		}
        //$condition['order_prom_type'] = 0;
        I('fast_flag') != '' ? $condition['c.fast_flag'] = I('fast_flag') : false;
        I('biaoshi_xian') != '' ? $condition['biaoshi_xian'] = ['like',"%".I('biaoshi_xian')."%"] : false;
        // dump($condition);
		$sort_order = 'a.order_id DESC';
        $count = M('order a')
		->field('a.order_id,b.goods_name,c.company,c.company_address,c.mobile')
		->join('ty_order_goods b on a.order_id=b.order_id','LEFT')
		->join('ty_users c on a.user_id=c.user_id','LEFT')
		->group('a.order_id')
		->where($condition)->select();
        $Page  = new AjaxPage(\count($count),20);
        $show = $Page->show();
        //获取订单列表
        $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);
        
 
		//获取主订单号

		foreach($orderList as $key=>$value){
			//去重复 
			$goods = M('order_goods a')->field('a.*,b.original_img,TRUNCATE(a.member_goods_price - (member_goods_price*(a.points/100)),3) AS goods_kou_price')
			->join('ty_goods b ON a.goods_id = b.goods_id')
			->where(array('a.order_id'=>$value['order_id']))
			->select();
			$tuihuo=M('return_goods')->where(' status <> 3 and order_id='.$value['order_id'])->select();$tuihuos=$tuihuo0=0;
			foreach($tuihuo as $vs){
				$tuihuo0+=\sanwei($vs['member_goods_price']*$vs['goods_num']);
				$tuihuos+=\sanwei($vs['member_goods_price']*$vs['goods_num']-$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100);
			}
            if($orderList[$key]['fast_flag'] && $orderList[$key]['shop_fast_flag']){
                $orderList[$key]['fast_text'] = '快线订单';
            }else{
                $orderList[$key]['fast_text'] = '';
            }
            if($value['mobile_staus'] == 0){
                $orderList[$key]['mobile'] = '********';
            }
			$orderList[$key]["tuihuo0"]=$tuihuo0;$orderList[$key]["tuihuo"]=$tuihuos;
			$orderList[$key]["ruku"]=M('order_jian')->where('order_id='.$value['order_id'].' and status_r=1')->count();
			$orderList[$key]["chuku"]=M('order_jian')->where('order_id='.$value['order_id'].' and status_c=1')->count();
            $orderList[$key]["biaoqian"]=$orderList[$key]["ruku"]!='0'? 'disabled="disabled"':'';
			$orderList[$key]["order_price"]=store_order_price($value['order_id']);//\print_r($orderList[$key]["order_price"])


            if($value['coupon_price'] > 0){
                //判断是不是我店铺优惠券
                $coupon = M('coupon')->where(['coupon_id'=>$value['coupon_id'],'store_id'=>STORE_ID])->count();
                if($coupon > 0){
                    $orderList[$key]['coupon_price'] = $value['coupon_price'];
                }else{
                    $orderList[$key]['coupon_price'] = 0;
                }
            }

			//$orderList[$key]["company"]=M('users')->where('user_id='.$value['user_id'])->getField('company');
			//$orderList[$key]["mobile"]=M('users')->where('user_id='.$value['user_id'])->getField('mobile');
			//$orderList[$key]["company_address"]=M('users')->where('user_id='.$value['user_id'])->getField('company_address');
			$tuihuo_num = 0;
			foreach($goods as $keys=>$vs){
                $goods_kou_total = sanwei($vs['goods_num'] * ($vs['member_goods_price'] - ($vs['member_goods_price'] * $vs['points'] /100)));
				$goods[$keys]['goods_kou_total']=$goods_kou_total;
				$tuihuo_num =M('return_goods')->where(' status <> 3 and order_id='.$value['order_id'].' and spec_key="'.$vs['spec_key'].'"')->sum('goods_num');
				$goods[$keys]['tuihuo_num']=$tuihuo_num;
                $spec_img = M('spec_image')->where(['spec_image_id'=>$vs['spec_key']])->getField('src');
                if($spec_img){
                    $goods[$keys]['original_img'] = C('MYOSS')['url2'].$spec_img;
                }else{
                    $goods[$keys]['original_img'] =  C('MYOSS')['url2'].$vs['original_img'];
                }

			}
        // dump($goods);
			$orderList[$key]["g_list"]=$goods;
            $orderList[$key]['biaoshi_xian'] = str_replace('快','',$orderList[$key]['biaoshi_xian']);
            $orderList[$key]["pay_name"]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$value['pay_code']))->getField('name');

		}
        // dump($orderList);
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
      /*
    *一键合并订单
    */
    public function oneClickMerge(){
        $where = [];
        $where['a.store_id'] = STORE_ID;
        $where['order_status'] = '0';
        $where['a.jian_count'] = 0;
        $where['a.stock_up'] = 1;
        $where['a.coupon_price'] = [['eq',0],['exp','IS NULL'],'or'];
        $list = M('order a')
		->field('c.user_id')
		->join('ty_order_goods b on a.order_id=b.order_id')
		->join('ty_users c on a.user_id=c.user_id','LEFT')
		->group('c.user_id')
		->where($where)
		->select();
	   
		foreach($list as $k=>$v){
		    $where['c.user_id'] = $v['user_id'];
		    //查看他的订单有没有多的
		    $list_two = M('order a')
    		->field('a.order_id,a.order_sn')
    		->join('ty_order_goods b on a.order_id=b.order_id')
    		->join('ty_users c on a.user_id=c.user_id','LEFT')
    		->group('a.order_id')
    		->where($where)
    		->select();
                
    	
    		if(count($list_two)>=2){
    		    $order_id = [];
    		    foreach ($list_two as $key=>$value){
    		        $order_id[] = $value['order_id'];
    		    }
    		   
    		    //这里合并
    		    $new_order_id=$old_order_id="";$new_amount=0;
    			foreach($order_id as $key=>$v){
    				if($key==0){
    					$new_order_id=$v;
    				}else{
    					$old_order_id.=$v.',';
    				}
    			}
    			$old_order_id=substr($old_order_id,0,strlen($old_order_id)-1);
    			
    			//$order_id=implode(',',$order_id);
    			$order_list=M('order')->where('order_id in('.$old_order_id.') and order_status=0 and pay_status=0')->select();
    			foreach ($order_list as $k=>$v){
                    if($v['coupon_price'] > 0){
                         echo '-2';exit;
                    }
                }
    			$new_order_user_id=M('order')->where('order_id='.$new_order_id.' and order_status=0')->find();
    			//找到收货人地区
    			//判断是否是同一个收货人。
    			foreach($order_list as $v){
    				if($new_order_user_id['user_id']!=$v['user_id']){
    					echo '-1';
    					exit;
    				}
                    $hborder_sn.=substr($v['order_sn'],-8).'<-';
    			}
                $userInfo = M('users')->where(['user_id'=>$v['user_id']])->find();
                sellerLog('合并订单：'.$hborder_sn);
    
    			if($order_list){
    				M('order_goods')->where('order_id in('.$old_order_id.')')->save([
    					'order_id'=>$new_order_id
    				]);
    				// dump($new_order_id);
    				M('order')->where('order_id in('.$old_order_id.')')->delete(); //删除多余主单
    				M('users_price')->where('order_id in('.$old_order_id.')')->delete();
                    //新旧orderyijia一起删除重新写入
                    M('order_yijia')
                        ->where('order_id in('.$old_order_id.')')
                        ->where(array('store_id'=>STORE_ID))
                        ->delete();
                    M('order_yijia')
                        ->where(array('order_id'=>$new_order_id,'store_id'=>STORE_ID))
                        ->delete();
                        
                        $data = M('order_goods')->where(['order_id'=>$new_order_id])->select();
                        $result = array();
                        foreach($data as $val){
                            $key = $val['spec_key'];
                            if(!isset($result[$key])){
                                $result[$key] = $val;
                            }else{
                                $result[$key]['goods_num'] += $val['goods_num'];
                            }
                        }
        
                        $result = array_values($result);
                        if($result){
                            M('order_goods')->where(['order_id'=>$new_order_id])->delete();
                            foreach ($result as $item){
                                M('order_goods')->add($item);
                            }
                        }
    
                    $order_goods=M('order_goods')->where('order_id='.$new_order_id)->select();//获取新主单产品
                     $new_kou = 0;
                     $yijias = 0;
                     $new_amount = 0;
                    foreach($order_goods as $v){ //计算单据产品价格
                        $fenbu_koudian = M('goods')->where("goods_id =".$v['goods_id'])->getField('fenbu_koudian');
                        if(!empty($fenbu_koudian)){
                            $fenbu_koudian = json_decode($fenbu_koudian,true);
                            $break = 0;
                            foreach ($fenbu_koudian as $kk=>$vv){
                                if($vv['fenbu_id'] == $userInfo['fenbu_id']){
                                    if(!empty($vv['fenbu_koudian']) && $vv['fenbu_koudian']!=0){
                                        $v['points'] = $vv['fenbu_koudian'];
                                        $break = 1;
                                        break;
                                    }
                                }
                            }
                            if($v['points'] != 0 && $break = 1){
                                M('order_goods')->where('rec_id='.$v['rec_id'])->setField(['points'=>$v['points']]);
                            }
                        }
                       
                       
    					$new_amount+=$v['member_goods_price']*$v['goods_num'];
                        //计算溢价
                        $yijias += (yj_price($v['goods_id'],$v['member_goods_price'],$userInfo['fenbu_id']))*$v['goods_num'];
                        $new_kou += sanwei($v['member_goods_price']*$v['goods_num']*$v['points']/100);
                       
                        $yijia=$v['yijia']==0 ? yj_price($v['goods_id'],$v['member_goods_price'],$userInfo['fenbu_id']) : $v['yijia'];
    //                    $order_goods[$key]['price']=$yijia;
                        if($yijia > 0){
                            M('order_goods')->where(['rec_id'=>$v['rec_id']])->setField(['yijia'=>$yijia]);
                            M("order_yijia")->data([
                                'order_sn'=>$new_order_user_id['order_sn'],
                                'order_id'=>$new_order_id,
                                'goods_id'=>$v['goods_id'],
                                'store_id'=>STORE_ID,
                                'consignee'=>$userInfo['nickname'],
                                'spec_key'=>$v['spec_key'],
                                'goods_num'=>$v['goods_num'],
                                'y_price'=>$v['member_goods_price'], //原价
                                'price'=>$yijia,
                                'fenbu_id'=>$userInfo['area_id'],
                                'add_time'=>\time()
                            ])->add(); //写入溢价分成表
                        }

    				}
    				M('users_price')->where('order_id='.$new_order_id)->save(['price'=>$new_amount+$yijias]);
    				
    				
    				M('order')->where('order_id='.$new_order_id)->save([
    					'goods_price'=>$new_amount,
    					'order_amount'=>$new_amount,
    					'total_amount'=>$new_amount,
                        'yijia_heji' =>$yijias,
                        'kou_price' =>$new_kou,
                        'tag'=>'<span style="color:#f88e2d">合并订单</span>'
    				]);
    				//修改溢价
    			}
			
    		}
		}
        
    }
    
    public function stockUp(){
        $order_ids = I('order_ids');
        $orderList = M('order')->where('order_id in ('.$order_ids.')')->select();
        foreach ($orderList as $k=>$v){
            if($v['jian_count'] <=0){
                $return_arr = array('code' => 0,'msg' => '订单存在标签为0的订单','data'  =>[]);
                $this->ajaxReturn($return_arr);
                exit;
            }
        }
        $return = M('order')->where('order_id in ('.$order_ids.') and order_status = 0 and jian_count>0')->save(['stock_up'=>2]);
        if(!empty($return)){
            $return_arr = array('code' => 1,'msg' => '备货成功','data'  =>[]);
            $this->ajaxReturn($return_arr);
            exit;
        }else{
            $return_arr = array('code' => 0,'msg' => '备货失败','data'  =>[]);
            $this->ajaxReturn($return_arr);
            exit;
        }
    }
    public function order_biaoqian(){
         $order_id = I('order_id');
         if(!empty($order_id)){
             M('order')->where(['order_id'=>$order_id])->setInc('dayin_biaoqian',1);
         }
         
    }
    
    /*
     * 待发货订单列表导出
    */
     public function daiexports(){
        $condition = array('a.store_id'=>STORE_ID); // 商家id
        $condition['order_status'] = 0;
        $timegap = I('timegap');
        I('fast_flag') != '' ? $condition['c.fast_flag'] = I('fast_flag') : false;
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        if($begin && $end){
            $condition['_string'] = 'add_time >='.$begin.' and add_time<='.$end;
        }
        $count = M('order a')
            ->field('b.goods_id')
            ->join('ty_order_goods b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->group('b.goods_id')
            ->where($condition)->select();

// 		dump($count);
        $goods_id = '';
        $goodsList = [];
        if(!empty($count)){
            foreach ($count as $k=>$v){
                $goodsData = M('order_goods a')
                    ->field('o.order_sn,a.goods_id,a.goods_name,a.spec_key_name,a.goods_num,a.spec_key,a.member_goods_price,g.last_name')
                    ->join('ty_order o on o.order_id = a.order_id','LEFT')
                    ->join('ty_users c on o.user_id = c.user_id','LEFT')
                    ->join('ty_goods g on g.goods_id = a.goods_id','LEFT')
                    ->where(['a.goods_id'=>$v['goods_id'],'a.store_id'=>STORE_ID,'o.order_status'=>0])
                    ->where($condition)
                    ->group('a.spec_key')
                    ->select();
                
                $goodsList[$k] = $goodsData;
                foreach ($goodsList[$k] as $key=>$value){
                    $SumGoods = M('order_goods a')
                        ->join('ty_order o on o.order_id = a.order_id','LEFT')
                        ->join('ty_users c on o.user_id = c.user_id','LEFT')
                        ->where(['a.goods_id'=>$v['goods_id'],'a.store_id'=>STORE_ID,'o.order_status'=>0,'spec_key'=>$value['spec_key']])
                        ->where($condition)
                        ->sum('goods_num');
                    $goodsList[$k][$key]['goods_num'] = $SumGoods;
                    if(!empty($value['last_name'])){
                        $goodsList[$k][$key]['goods_name'] = $value['last_name'];
                    }
                }

            }
        }
// 		dump($goodsList);
        $mergedArray = [];
        foreach ($goodsList as $subArray) {
            $mergedArray = array_merge($mergedArray, $subArray);
        }
        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品规格</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品单价</td>';
        $strTable .= '</tr>';


        foreach($mergedArray as $k=>$val){

            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['goods_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['spec_key_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['goods_num'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['member_goods_price'].'</td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($goodsList);
        downloadExcel($strTable,'daiorder');
        exit();

    }
    
     //导出订单
    public function guanjiapo()
    {
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            // $begin = $end - 86400*3+60;
        }
        // dump($end);
        // dump($begin);
        // die;
        if(empty(!I('goods_name'))){
            $this->error('不支持产品条件提交导出!');exit;
        }
        
        // if($end-$begin > 86400*3){
        //     $this->error('系统只支持2天的数据导出！');exit;
        // }
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");
        import("Org.Util.PHPExcel.Writer.Excel2007");
        // 搜索条件 STORE_ID
        $condition = array('o.store_id'=>STORE_ID); // 商家id
        I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") OR (a.mobile like "%'.I('consignee').'%")';
        
        if($begin && $end){
            $condition['o.add_time'] = array('between',"$begin,$end");
        }
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;

        if(I('dayin_store')=="0"){
            $condition['dayin_store']=0;
        }elseif(I('dayin_store')== '1'){
            $condition['dayin_store']=array('gt',0);
        }

        $condition['o.order_status'] = array('in','0,1,2,4');
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objActSheet = $objPHPExcel->getActiveSheet();

        $objActSheet->setCellValue('A1', '录单日期');
        $objActSheet->setCellValue('B1', '单据编号');
        $objActSheet->setCellValue('C1', '单据类型');
        $objActSheet->setCellValue('D1', '往来单位编号');
        $objActSheet->setCellValue('E1', '往来单位全名');
        $objActSheet->setCellValue('F1', '经手人编号');
        $objActSheet->setCellValue('G1', '经手人全名');
        $objActSheet->setCellValue('H1', '部门编号');
        $objActSheet->setCellValue('I1', '部门全名');
        $objActSheet->setCellValue('J1', '收/付款日期');
        $objActSheet->setCellValue('K1', '仓库编号');
        $objActSheet->setCellValue('L1', '仓库全名');
        $objActSheet->setCellValue('M1', '摘要');
        $objActSheet->setCellValue('N1', '附加说明');
        $objActSheet->setCellValue('O1', '制单人编号');
        $objActSheet->setCellValue('P1', '制单人');
        $objActSheet->setCellValue('Q1', '收/付款账户编号');
        $objActSheet->setCellValue('R1', '收/付款金额');
        $objActSheet->setCellValue('S1', '交货日期(订单专用)');
        $objActSheet->setCellValue('T1', '优惠');
        $objActSheet->setCellValue('U1', '商品编号');
        $objActSheet->setCellValue('V1', '商品全名');
        $objActSheet->setCellValue('W1', '仓库编号');
        $objActSheet->setCellValue('X1', '仓库全名');
        $objActSheet->setCellValue('Y1', '单位');
        $objActSheet->setCellValue('Z1', '生产日期');
        $objActSheet->setCellValue('AA1', '批号');
        $objActSheet->setCellValue('AB1', '数量');
        $objActSheet->setCellValue('AC1', '单价');
        $objActSheet->setCellValue('AD1', '金额');
        $objActSheet->setCellValue('AE1', '折扣');
        $objActSheet->setCellValue('AF1', '折后单价');
        $objActSheet->setCellValue('AG1', '折后金额');
        $objActSheet->setCellValue('AH1', '税率');
        $objActSheet->setCellValue('AI1', '税额');
        $objActSheet->setCellValue('AJ1', '含税单价');
        $objActSheet->setCellValue('AK1', '含税金额');
        $objActSheet->setCellValue('AL1', '单据备注');
        $objActSheet->setCellValue('AM1', '对方商品编号');
        $i=2;
        // dump($condition);
        // die;
        $orderList=M('order_goods a')
            ->field('a.*,b.company,o.order_sn,gp.spu,gp.sku')
            ->join('ty_order o on o.order_id = a.order_id','left')
            ->join('ty_spec_goods_price gp on gp.key = a.spec_key','left')
            ->join('ty_users b on o.user_id=b.user_id')
            ->where($condition)
            ->order('o.add_time asc')->select();
        // dump($orderList);
        // die;
        foreach($orderList as $k=>$v){
            $objActSheet->setCellValue('A'.$i, date('Y-m-d'));
            $objActSheet->setCellValue('B'.$i, 'ytd'.$v['order_sn']);
            $objActSheet->setCellValue('C'.$i, '销售单');
            $objActSheet->setCellValue('D'.$i, '02002');
            $objActSheet->setCellValue('E'.$i, $v['company']);
            $objActSheet->setCellValue('F'.$i, '000000000');
            $objActSheet->setCellValue('G'.$i, '');
            $objActSheet->setCellValue('H'.$i, '');
            $objActSheet->setCellValue('I'.$i, '');
            $objActSheet->setCellValue('J'.$i, '');
            $objActSheet->setCellValue('K'.$i, '01');
            $objActSheet->setCellValue('L'.$i, '');
            $objActSheet->setCellValue('M'.$i, '');
            $objActSheet->setCellValue('N'.$i, '');
            $objActSheet->setCellValue('O'.$i, '');
            $objActSheet->setCellValue('P'.$i, '');
            $objActSheet->setCellValue('Q'.$i, '');
            $objActSheet->setCellValue('R'.$i, '');
            $objActSheet->setCellValue('S'.$i, '');
            $objActSheet->setCellValue('T'.$i, '');
            $objActSheet->setCellValue('U'.$i, $v['sku']);
            $objActSheet->setCellValue('V'.$i, '');
            $objActSheet->setCellValue('W'.$i, '');
            $objActSheet->setCellValue('X'.$i, '');
            $objActSheet->setCellValue('Y'.$i, $v['spu']);
            $objActSheet->setCellValue('Z'.$i, '');
            $objActSheet->setCellValue('AA'.$i, '');
            $objActSheet->setCellValue('AB'.$i, $v['goods_num']);
            $objActSheet->setCellValue('AC'.$i, sanwei($v['member_goods_price']+$v['yijia']));
            $objActSheet->setCellValue('AD'.$i, sanwei(sanwei($v['member_goods_price']+$v['yijia'])*$v['goods_num']));
            $objActSheet->setCellValue('AE'.$i, '');
            $objActSheet->setCellValue('AF'.$i, '');
            $objActSheet->setCellValue('AG'.$i, '');
            $objActSheet->setCellValue('AH'.$i, '');
            $objActSheet->setCellValue('AI'.$i, '');
            $objActSheet->setCellValue('AJ'.$i, '');
            $objActSheet->setCellValue('AK'.$i, '');
            $objActSheet->setCellValue('AL'.$i, '');
            $objActSheet->setCellValue('AM'.$i, '');

            $i++;
        }
       
        $fileName = '联鑫壹天达管家婆单据';
        $date = date("Y-m-d",time());
        $fileName .= "_{$date}.xls";
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        $objPHPExcel->getActiveSheet()->setTitle('viateams');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

       /*
     * 待发货订单列表导出
    */
    public function orderexport_order(){
         
        
         $timegap = I('timegap');
        if($timegap){
        	$gap = explode(' - ', $timegap);
        	$begin = strtotime($gap[0]);
        	$end = strtotime($gap[1]);
        }
        // 搜索条件 STORE_ID
        $condition = array('o.store_id'=>STORE_ID); // 商家id
		I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") OR (a.mobile like "%'.I('consignee').'%")';
		I('goods_name') ? $condition['goods_name'] = array('like','%'.trim(I('goods_name')).'%'): false;
        if($begin && $end){
        	$condition['add_time'] = array('between',"$begin,$end");
        // 	$condition['_string'] = 'add_time >='.$begin.' and add_time<='.$end;
        }
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        //I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
		if(I('order_status') == '3'){
			$condition['order_status'] = array('in','3,5');
		}elseif(I('order_status') == '4'){
		    $condition['order_status'] = 0;
		    $condition['shipping_status'] = 0;
		    $condition['stock_up'] = 2;
		}elseif(I('order_status') == '0'){
		    $condition['order_status'] = 0;
		    $condition['shipping_status'] = 0;
		    $condition['stock_up'] = 1;
		}elseif(I('order_status') != ''){
			$condition['order_status'] = I('order_status');
		}
		
		if(I('order_status') == 99){
		    $condition['order_status'] = array('not in','3,5');
		}
		I('fast_flag') != '' ? $condition['c.fast_flag'] = I('fast_flag') : false;
	
			import("Org.Util.PHPExcel");
			import("Org.Util.PHPExcel.Worksheet.Drawing");
			import("Org.Util.PHPExcel.Writer.Excel2007");
			
			$objPHPExcel = new \PHPExcel();
			$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
			$objPHPExcel->setActiveSheetIndex(0);
			 $objActSheet = $objPHPExcel->getActiveSheet();
			        $objActSheet->setCellValue('A1', '*单据日期');
                    // 设置要添加注释的单元格，例如：A1
                    $objCell = $objActSheet->getCell('A1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('A1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('VoucherDate');
			        $objActSheet->setCellValue('B1', '外部单据号');
                    // $objActSheet->getComment( 'B1')->getText()->createTextRun('ExternalVoucherCode');
                     // 获取A1单元格
                    $objCell = $objActSheet->getCell('B1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('B1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('ExternalVoucherCode');
			        $objActSheet->setCellValue('C1', '*业务员编码');
                    // $objActSheet->getComment( 'C1')->getText()->createTextRun('Clerk');
                    // 获取A1单元格
                    $objCell = $objActSheet->getCell('C1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('C1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('Clerk');
                    
			        $objActSheet->setCellValue('D1', '业务员');
			     //   $objActSheet->getComment( 'D1')->getText()->createTextRun('ClerkName');
			         // 获取A1单元格
                    $objCell = $objActSheet->getCell('D1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('D1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('ClerkName');
			        $objActSheet->setCellValue('E1', '*客户编码');
			     //   $objActSheet->getComment( 'E1')->getText()->createTextRun('Customer');
			         // 获取A1单元格
                    $objCell = $objActSheet->getCell('E1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('E1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('Customer');
					$objActSheet->setCellValue('F1', '客户');
				// 	$objActSheet->getComment( 'F1')->getText()->createTextRun('CustomerName');
					 // 获取A1单元格
                    $objCell = $objActSheet->getCell('F1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('F1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('CustomerName');
					$objActSheet->setCellValue('G1', '发票号');
					 // 获取A1单元格
                    $objCell = $objActSheet->getCell('G1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('G1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleInvoiceNo');
                    
					$objActSheet->setCellValue('H1', '发票介质');
				
                    // 获取A1单元格
                    $objCell = $objActSheet->getCell('H1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('H1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleInvoiceMedia');
                    
                    
					$objActSheet->setCellValue('I1', '结算客户编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('I1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('I1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SettleCustomer');
                    
				
                  
                    
					$objActSheet->setCellValue('J1', '结算客户');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('J1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('J1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SettleCustomerName');
                   
				
                    
					$objActSheet->setCellValue('K1', '部门编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('K1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('K1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('Department');
                    
					$objActSheet->setCellValue('L1', '部门');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('L1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('L1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('DepartmentName');
                    
					$objActSheet->setCellValue('M1', '送货日期');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('M1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('M1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SendDate');
                    
					$objActSheet->setCellValue('N1', '*业务类型编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('N1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('N1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('BusinessType');
                    
					$objActSheet->setCellValue('O1', '业务类型');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('O1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('O1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('BusinessTypeName');
                    
					$objActSheet->setCellValue('P1', '抹零');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('P1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('P1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('origAllowances');
                    
					$objActSheet->setCellValue('Q1', '结算方式');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('Q1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('Q1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('priuserdefnvc1');
                    
					$objActSheet->setCellValue('R1', '收款方式');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('R1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('R1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('ReciveType');
                    
					$objActSheet->setCellValue('S1', '发货方式');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('S1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('S1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('DeliveryMode');
                    
					$objActSheet->setCellValue('T1', '联系电话');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('T1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('T1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('ContactPhone');
                    
					$objActSheet->setCellValue('U1', '*单据编号');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('U1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('U1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('Code');
                    
					$objActSheet->setCellValue('V1', '送货地址');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('V1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('V1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('Address');
                    
					$objActSheet->setCellValue('W1', '联系人');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('W1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('W1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('LinkMan');
					$objActSheet->setCellValue('X1', '客户手机号');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('X1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('X1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('CustomerPhone');
                    
					$objActSheet->setCellValue('Y1', '送货人编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('Y1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('Y1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SendPerson');
                    
					$objActSheet->setCellValue('Z1', '送货人');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('Z1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('Z1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SendPersonName');
                    
					$objActSheet->setCellValue('AA1', '收款到期日');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AA1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AA1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('RecivingMaturity');
                    
					$objActSheet->setCellValue('AB1', '代收单位');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AB1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AB1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('priuserdefnvc2');
                    
					$objActSheet->setCellValue('AC1', '出库类别编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AC1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AC1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('RdStyle');
                    
					$objActSheet->setCellValue('AD1', '出库类别');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AD1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AD1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('RdStyleName');
                    
					$objActSheet->setCellValue('AE1', '自动生成发票');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AE1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AE1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('IsAutoGenerateInvoice');
                    
					$objActSheet->setCellValue('AF1', '*票据类型');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AF1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AF1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('InvoiceType');
                    
					$objActSheet->setCellValue('AG1', '点货人');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AG1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AG1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('priuserdefnvc6');
                    
					$objActSheet->setCellValue('AH1', '理数人');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AH1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AH1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('priuserdefnvc5');
					$objActSheet->setCellValue('AI1', '件数');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AI1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AI1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('priuserdefdecm1');
					$objActSheet->setCellValue('AJ1', '代收金额及备注');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AJ1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AJ1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('priuserdefnvc3');
					$objActSheet->setCellValue('AK1', '备注');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AK1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AK1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('Memo');
					$objActSheet->setCellValue('AL1', '仓库编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AL1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AL1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_Warehouse');
					$objActSheet->setCellValue('AM1', '仓库');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AM1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AM1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_WarehouseName');
					$objActSheet->setCellValue('AN1', '项目编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AN1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AN1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_Project');
					$objActSheet->setCellValue('AO1', '项目');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AO1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AO1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_ProjectName');
					$objActSheet->setCellValue('AP1', '客户存货名称');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AP1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AP1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_PartnerInventoryName');
					$objActSheet->setCellValue('AQ1', '客户存货编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AQ1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AQ1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_PartnerInventoryCode');
					$objActSheet->setCellValue('AR1', '存货编码');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AR1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AR1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_Inventory');
					$objActSheet->setCellValue('AS1', '存货名称');
                    // 获取A1单元格
                    $objCell = $objActSheet->getCell('AS1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AS1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_InventoryNam');
					$objActSheet->setCellValue('AT1', '销售单位');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AT1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AT1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_Unit');
					$objActSheet->setCellValue('AU1', '*数量');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AU1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AU1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_Quantity');
					$objActSheet->setCellValue('AV1', '赠品');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AV1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AV1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_IsPresent');
					$objActSheet->setCellValue('AW1', '报价');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AW1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AW1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_OrigPrice');
					$objActSheet->setCellValue('AX1', '换算率');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AX1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AX1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_UnitExchangeRate');
					$objActSheet->setCellValue('AY1', '计量单位2');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AY1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AY1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_Unit2');
					$objActSheet->setCellValue('AZ1', '数量2');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('AZ1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('AZ1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_Quantity2');
					$objActSheet->setCellValue('BA1', '批号');// 获取A1单元格
                    $objCell = $objActSheet->getCell('BA1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BA1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_Batch');
					$objActSheet->setCellValue('BB1', '生产日期');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BB1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BB1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_ProductionDate');
					$objActSheet->setCellValue('BC1', '失效日期');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BC1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BC1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_ExpiryDate');
					$objActSheet->setCellValue('BD1', '税率%');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BD1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BD1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_TaxRate');
					$objActSheet->setCellValue('BE1', '含税单价');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BE1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BE1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_OrigTaxPrice');
					$objActSheet->setCellValue('BF1', '含税金额');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BF1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BF1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_OrigTaxAmount');
					$objActSheet->setCellValue('BG1', '退补标志');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BG1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BG1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_RefundDifferenceFlag');
					$objActSheet->setCellValue('BH1', '交货日期');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BH1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BH1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_DeliveryDate');
					$objActSheet->setCellValue('BI1', '折扣%');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BI1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BI1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_DiscountRate');
					$objActSheet->setCellValue('BJ1', '手工确定成本');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BJ1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BJ1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_IsManualCost');
					$objActSheet->setCellValue('BK1', '优惠金额');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BK1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BK1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_priuserdefdecm2');
					$objActSheet->setCellValue('BL1', '成本金额');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BL1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BL1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_SaleOrderCode');
					$objActSheet->setCellValue('BM1', '销售订单号');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BM1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BM1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_SaleOrderCode');
					$objActSheet->setCellValue('BN1', '成本价');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BN1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BN1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_CostPrice');
					$objActSheet->setCellValue('BO1', '实收金额');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BO1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BO1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_priuserdefdecm1');
					$objActSheet->setCellValue('BP1', '备注');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BP1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BP1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_DetailMemo');
					$objActSheet->setCellValue('BQ1', '存货描述');
					// 获取A1单元格
                    $objCell = $objActSheet->getCell('BQ1');
                    // 创建批注对象
                    $objComment = $objActSheet->getComment('BQ1');
                    // 设置批注的作者和内容
                    $objComment->setAuthor('DELLSERVER$');
                    $objComment->getText()->createText('SaleDeliveryDetails_priuserdefnvc1');
					
					$i=2;
					 $orderList = M('order_goods g')
					 ->field('g.*,o.*,c.*,sp.*,sp.sku as sku')
                    ->join('ty_order o on o.order_id = g.order_id','LEFT')
		            ->join('ty_users c on o.user_id=c.user_id','LEFT')
		            ->join('ty_spec_goods_price  sp on sp.key=g.spec_key','LEFT')
                    ->where($condition)
                    ->select();
				// 	$orderList=M('order a')
				// 	->field('a.*,b.company')
				// 	->join('ty_users b on a.user_id=b.user_id')
				// 	->where('a.order_id in('.$ids.')')->select();
			
				$rand = rand(10000,99999);
				$jine = 0;
					foreach($orderList as $val){
					    $jine +=geshi(($val['member_goods_price']-($val['member_goods_price']*($val['points']/100)))*$val['goods_num']);
				// 	$orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
					$ty_spec_goods_price = D('spec_goods_price')->where(['key'=>$val['spec_key']])->getField('spu');
    						$objActSheet->setCellValue('A'.$i, date('Y-m-d',time()));
    						$objActSheet->setCellValue('B'.$i, '');
    						$objActSheet->setCellValue('C'.$i, '010');
    						$objActSheet->setCellValue('D'.$i, '');
    						$objActSheet->setCellValue('E'.$i, '2.07.06.002');
    						$objActSheet->setCellValue('F'.$i, '');
    						$objActSheet->setCellValue('G'.$i, '');
    						$objActSheet->setCellValue('H'.$i, '纸票');
    						$objActSheet->setCellValue('I'.$i, '');
    						$objActSheet->setCellValue('J'.$i, '');
    						$objActSheet->setCellValue('K'.$i, '');
    						$objActSheet->setCellValue('L'.$i, '');
    						$objActSheet->setCellValue('M'.$i, '');
    						$objActSheet->setCellValue('N'.$i, '15');
    						$objActSheet->setCellValue('O'.$i, '普通销售');
    						$objActSheet->setCellValue('P'.$i, '');
    						$objActSheet->setCellValue('Q'.$i, '');
    						$objActSheet->setCellValue('R'.$i, '');
    						$objActSheet->setCellValue('S'.$i, '');
    						$objActSheet->setCellValue('T'.$i, '');
    						$objActSheet->setCellValue('U'.$i, '联鑫壹天达_'.date('Y-m-d',time()).'_'.$rand);
    						$objActSheet->setCellValue('V'.$i, '');
    						$objActSheet->setCellValue('W'.$i, '');
    						$objActSheet->setCellValue('X'.$i, '');
    						$objActSheet->setCellValue('Y'.$i, '');
    						$objActSheet->setCellValue('Z'.$i, '');
    						$objActSheet->setCellValue('AA'.$i, '');
    						$objActSheet->setCellValue('AB'.$i, '');
    						$objActSheet->setCellValue('AC'.$i, '');
    						$objActSheet->setCellValue('AD'.$i, '');
    						$objActSheet->setCellValue('AE'.$i, '');
    						$objActSheet->setCellValue('AF'.$i, '专用发票');
    						$objActSheet->setCellValue('AG'.$i, '');
    						$objActSheet->setCellValue('AH'.$i, '');
    						$objActSheet->setCellValue('AI'.$i, '');
    						$objActSheet->setCellValue('AJ'.$i, '');
    						$objActSheet->setCellValue('AK'.$i, '');
    						$objActSheet->setCellValue('AL'.$i, '001');
    						$objActSheet->setCellValue('AM'.$i, '');
    						$objActSheet->setCellValue('AN'.$i, '');
    						$objActSheet->setCellValue('AO'.$i, '');
    						$objActSheet->setCellValue('AP'.$i, '');
    						$objActSheet->setCellValue('AQ'.$i, '');
    						$objActSheet->setCellValue('AR'.$i, $val['sku']);
    						$objActSheet->setCellValue('AS'.$i, '');
    						$objActSheet->setCellValue('AT'.$i, $ty_spec_goods_price);
    						$objActSheet->setCellValue('AU'.$i, geshi((int)$val['goods_num']));
    						$objActSheet->setCellValue('AV'.$i, '');
    						$objActSheet->setCellValue('AW'.$i, '');
    						$objActSheet->setCellValue('AX'.$i, '');
    						$objActSheet->setCellValue('AY'.$i, '');
    						$objActSheet->setCellValue('AZ'.$i, '');
    						$objActSheet->setCellValue('BA'.$i, '');
    						$objActSheet->setCellValue('BB'.$i, '');
    						$objActSheet->setCellValue('BC'.$i, '');
    						$objActSheet->setCellValue('BD'.$i, '');
    						$objActSheet->setCellValue('BE'.$i, '');
    						$objActSheet->setCellValue('BF'.$i, geshi(($val['member_goods_price']-($val['member_goods_price']*($val['points']/100)))*$val['goods_num']));
    						$objActSheet->setCellValue('BG'.$i, '');
    						$objActSheet->setCellValue('BH'.$i, '');
    						$objActSheet->setCellValue('BI'.$i, '');
    						$objActSheet->setCellValue('BJ'.$i, '');
    						$objActSheet->setCellValue('BK'.$i, '');
    						$objActSheet->setCellValue('BL'.$i, '');
    						$objActSheet->setCellValue('BM'.$i, '');
    						$objActSheet->setCellValue('BN'.$i, '');
    						$objActSheet->setCellValue('BO'.$i, '');
    						$objActSheet->setCellValue('BP'.$i, $val['goods_name'].'_'.$val['spec_key_name']);
    						$objActSheet->setCellValue('BQ'.$i, '');
    						$i++;
					}
				
					  $fileName = '联鑫壹天达单据';
					        $date = date("Y-m-d",time());
					        $fileName .= "_{$date}.xlsx";
					        $fileName = iconv("utf-8", "gb2312", $fileName);
					        //重命名表
					        $objPHPExcel->getActiveSheet()->setTitle('销售单');
		                    
					        
					        $sheet2 = $objPHPExcel->createSheet(); // 创建新的工作表，并返回索引
                            $sheet2->setTitle('现结');
					        $sheet2->setCellValue('A1', '所属销货单单据编号');
                            $sheet2->setCellValue('B1', '*结算方式编码');
                            // $sheet2->getComment( 'B1')->getText()->createTextRun('SettleStyle');
                            // 获取A1单元格
                            $objCell = $sheet2->getCell('B1');
                            // 创建批注对象
                            $objComment = $sheet2->getComment('B1');
                            // 设置批注的作者和内容
                            $objComment->setAuthor('DELLSERVER$');
                            $objComment->getText()->createText('SettleStyle');
                            // $objComment->getText()->createText('SettleStyle');
                            
                            $sheet2->setCellValue('C1', '结算方式');
                            // $sheet2->getComment( 'C1')->getText()->createTextRun('SettleStyleName');
                            // 获取A1单元格
                            $objCell = $sheet2->getCell('C1');
                            // 创建批注对象
                            $objComment = $sheet2->getComment('C1');
                            // 设置批注的作者和内容
                            $objComment->setAuthor('DELLSERVER$');
                            $objComment->getText()->createText('SettleStyleName');
                            
                            // $objComment->getText()->createText('SettleStyleName');
                            $sheet2->setCellValue('D1', '*账号名称');
                            // $sheet2->getComment( 'D1')->getText()->createTextRun('BankAccount');
                            // 获取A1单元格
                            $objCell = $sheet2->getCell('D1');
                            // 创建批注对象
                            $objComment = $sheet2->getComment('D1');
                            // 设置批注的作者和内容
                            $objComment->setAuthor('DELLSERVER$');
                            $objComment->getText()->createText('BankAccount');
                            
                            // $objComment->getText()->createText('BankAccount');
                            $sheet2->setCellValue('E1', '*收款金额');
                            // $sheet2->getComment( 'E1')->getText()->createTextRun('OrigAmount');
                            // 获取A1单元格
                            $objCell = $sheet2->getCell('E1');
                            // 创建批注对象
                            $objComment = $sheet2->getComment('E1');
                            // 设置批注的作者和内容
                            $objComment->setAuthor('DELLSERVER$');
                            $objComment->getText()->createText('OrigAmount');
                            
                            // $objComment->getText()->createText('OrigAmount');
                            $sheet2->setCellValue('F1', '*票据号');
                             // 获取A1单元格
                            // $sheet2->getComment( 'F1')->getText()->createTextRun('BillNo');
                            // 获取A1单元格
                            $objCell = $sheet2->getCell('F1');
                            // 创建批注对象
                            $objComment = $sheet2->getComment('F1');
                            // 设置批注的作者和内容
                            $objComment->setAuthor('DELLSERVER$');
                            $objComment->getText()->createText('BillNo');
					        
					        $sheet2->setCellValue('A2', '联鑫壹天达_'.date('Y-m-d',time()).'_'.$rand);
					        $sheet2->setCellValue('B2', 1);
					        $sheet2->setCellValue('C2', '');
					        $sheet2->setCellValue('D2', '现金');
					        $sheet2->setCellValue('E2', $jine);
					        $sheet2->setCellValue('F2', '');
					        
					       // header('Content-Type: application/vnd.ms-excel');
					       // header("Content-Disposition: attachment;filename=\"$fileName\"");
					       // header('Cache-Control: max-age=0');
					        
					         header("Pragma: public");
                            header("Expires: 0");
                            header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
                            header("Content-Type:application/force-download");
                            header("Content-Type:application/vnd.ms-execl");
                            header("Content-Type:application/octet-stream");
                            header("Content-Type:application/download");;
                            header("Content-Disposition: attachment;filename=\"$fileName\"");
                            header("Content-Transfer-Encoding:binary");
					        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
					        $objWriter->save('php://output'); //文件通过浏览器下载
			exit;
        
        
        
        $timegap = I('timegap');
        if($timegap){
        	$gap = explode(' - ', $timegap);
        	$begin = strtotime($gap[0]);
        	$end = strtotime($gap[1]);
        }
        // 搜索条件 STORE_ID
        $condition = array('o.store_id'=>STORE_ID); // 商家id
		I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") OR (a.mobile like "%'.I('consignee').'%")';
		I('goods_name') ? $condition['goods_name'] = array('like','%'.trim(I('goods_name')).'%'): false;
        if($begin && $end){
        	$condition['add_time'] = array('between',"$begin,$end");
        }
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        //I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
		if(I('order_status') == '3'){
			$condition['order_status'] = array('in','3,5');
		}elseif(I('order_status') != ''){
			$condition['order_status'] = I('order_status');
		}
        //$condition['order_prom_type'] = 0;
                
        $orderList = M('order_goods g')
        ->join('ty_order o on o.order_id = g.order_id','LEFT')
        ->where($condition)
        ->select();
     
//         //获取订单列表
//         $orderList = M('order a')
// 		->field('a.*,c.company,c.company_address,c.mobile,c.fast_flag')
// 		->join('ty_users c on a.user_id=c.user_id','LEFT')
// 		->group('a.order_id')
// 		->where($condition)->order('order_id desc')->select();
		
		

    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">*单据日期</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">外部单据号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">*业务员编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">业务员</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">*客户编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">发票号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">发票介质</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">结算客户编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">结算客户</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">部门编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">部门</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">送货日期</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">*业务类型编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">业务类型</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">抹零</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">结算方式</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收款方式</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">发货方式</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">联系电话</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">*单据编号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">*送货地址</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">联系人</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户手机号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">送货人编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">送货人</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收款到期日</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">代收单位</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">出库类别编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">出库类别</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">自动生成发票</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">*票据类型</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">点货人</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">理数人</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">件数</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">代收金额及备注</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">备注</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">仓库编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">仓库</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">项目编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">项目</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户存货名称</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户存货编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">存货编码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">存货名称</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">销售单位</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">*数量</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">赠品</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">报价</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">换算率</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">计量单位2</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量2</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">批号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">生产日期</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">失效日期</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">税率%</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">含税单价</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">含税金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">退补标志</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">交货日期</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">折扣%</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">手工确定成本</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">优惠金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">成本金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">销售订单号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">成本价</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">实收金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">备注</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">存货描述</td>';
    	$strTable .= '</tr>';
    	
        $rand = rand(10000,99999);
    	foreach($orderList as $k=>$val){
	            $ty_spec_goods_price = M('spec_goods_price')->where(['key'=>$val['spec_key']])->getField('spu');
		       	$strTable .= '<tr>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.date('Y-m-d',time()).'</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;010</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;2.07.06.002</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;纸票</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;15</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;普通销售</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;联鑫壹天达_'.date('Y-m-d',time()).'_'.$rand.'</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;专用发票</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;001</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['sku'].'</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$ty_spec_goods_price.'</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['goods_num'].'</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.geshi($val['member_goods_price']*$val['goods_num']).'</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['goods_name'].' '.$val['spec_key_name'].'</td>';
        		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;</td>';
        		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	$count = count($orderList);
    	unset($orderList);
    	downloadExcel($strTable,'共有订单'.$count.'_联鑫壹天达');
    	exit();
		
    }
    
    
    /*
     * ajax 发货订单列表
    */
    public function ajaxdelivery(){
    	$orderLogic = new OrderLogic();
    	$condition = array('store_id'=>STORE_ID);
    	I('consignee') ? $condition['consignee'] = trim(I('consignee')) : false;
    	I('order_sn') != '' ? $condition['order_sn'] = trim(I('order_sn')) : false;
    	$shipping_status = I('shipping_status');
    	$condition['shipping_status'] = empty($shipping_status) ? array('neq',1) : $shipping_status;
		$condition['order_status'] = array('in','1,2,4');
    	$count = M('order')->where($condition)->count();
    	$Page  = new AjaxPage($count,10);
    	$show = $Page->show();
    	$orderList = M('order')->where($condition)->limit($Page->firstRow.','.$Page->listRows)->order('add_time DESC')->select();
    	$this->assign('orderList',$orderList);
    	$this->assign('page',$show);// 赋值分页输出
    	$this->display();
    }
    
    /**
     * 订单详情
     * @param int $id 订单id
     */
    public function detail($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $button = $orderLogic->getOrderButton($order);
        // 获取操作记录
        $action_log = M('order_action')->where(array('order_id'=>$order_id))->order('log_time desc')->select();
		$order['jian_list']=M('order_jian')->where(array('order_id'=>$order_id))->order('id asc')->select();

        $split = count($orderGoods) >1 ? 1 : 0;
		$points=0;
        foreach ($orderGoods as $key=>$val){
            $spec_img = M('spec_image')->where(['spec_image_id'=>$val['spec_key']])->getField('src');
            if($spec_img){
                $orderGoods[$key]['original_img'] =  C('MYOSS')['url2'].$spec_img;
            }else{
                $orderGoods[$key]['original_img'] =  C('MYOSS')['url2'].$val['original_img'];
            }
        	if($val['goods_num']>1){
        		$split = 1;
				$points_count+=\sanwei($val['points']*$val['member_goods_price']*$val['goods_num']/100);
        	}
        }
		if($order['dai_type']==2){
			$points_count=\sanwei($orderGoods[0]['points']*$order['order_amount']/100);
		}
		$mobile_staus = M('store')->where(['store_id'=>STORE_ID])->getField('mobile_staus');
		if($mobile_staus == 0){
		    $order['mobile'] = '****';
		}
        $this->assign('order',$order);
        $this->assign('action_log',$action_log);
        $this->assign('orderGoods',$orderGoods);
		$this->assign('points_count',$points_count);
        $this->assign('split',$split);
        $this->assign('button',$button);
        $this->display();
    }
	
    public function shadow(){
		$order_list=M('order')->where('store_id='.STORE_ID.' and order_status in(0,1,2,4)')->limit(1000)->order('order_amount desc')->select(); 
		foreach($order_list as $v){
			$goodslist=M('order_goods')->where('order_id='.$v['order_id'])->select();
			$shiji=0;
			foreach($goodslist as $vs){
				$shiji+=\sanwei($vs['goods_num']*$vs['member_goods_price']);
			}
			$pd=$v['order_amount']-sanwei($shiji);
			if($pd!=0){echo floatval($v['order_amount'])-floatval($shiji).'<br/>';
				echo "单号：".$v['order_sn']." 单据价格：<span style='color:blue'>".floatval($v['order_amount'])."</span> , 实际价格：<span style='color:red'>".floatval($shiji)."</span><br/>";
			}
			
		}
	}
    /*
     * 拆分订单
     */
    public function split_order(){
        
    	$order_id = I('order_id'); 
    	$orderLogic = new OrderLogic();
    	$order = $orderLogic->getOrderInfo($order_id);
    	if($order['shipping_status'] != 0){
    		$this->error('已发货订单不允许编辑');
    		exit;
    	}
    	if($order['coupon_price'] > 0){
    	    $this->error('有优惠券不允许拆分');
    		exit;
    	}
    	$orderGoods = $orderLogic->getOrderGoods($order_id);
    	if(IS_POST){
    		$data = I('post.');
            $userInfo = M('users')->where(['user_id'=>$orderGoods['user_id']])->find();
            //################################先处理原单剩余商品和原订单信息
    		$old_goods = I('old_goods');
    		foreach ($orderGoods as $val){
    			if(empty($old_goods[$val['rec_id']])){
    				M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
    			}else{
    				//修改商品数量
    				if($old_goods[$val['rec_id']] != $val['goods_num']){
    					$val['goods_num'] = $old_goods[$val['rec_id']];
    					M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
    				}
    				$oldArr[] = $val;//剩余商品
    			}
    			$all_goods[$val['rec_id']] = $val;//所有商品信息
    		}
            try {
                M()->startTrans();
                $result = calculate_price($order['user_id'],$oldArr,array(STORE_ID => $order['shipping_code']),0,$order['province'],$order['city'],$order['district'],0,0,0,0,'线下',11);
                M()->commit();


    		if($result['status'] < 0)
    		{
    			$this->error($result['msg']);
    		}
    		//修改订单费用
    		$res['goods_price']    = $result['result']['goods_price']; // 商品总价
    		$res['order_amount']   = $result['result']['order_amount']; // 应付金额
    		$res['total_amount']   = $result['result']['total_amount']; // 订单总价
			$res['yijia_heji']   = $result['result']['yijia_heji_s']; // 订单yijia
			$res['kou_price']   = $result['result']['kou_price_s']; // 订单收益
			$res['jian_count']   = 0; // 订单标签数
			$res['ruku_count']   = 0; // 入库清空
			$res['chuku_count']   = 0; // 出库清空
			$res['ruku_last_time']   = ''; // 入库清空
			$res['chuku_last_time']   = ''; // 出库清空
			$res['tag']   = '<span style="color:#f88e2d">拆单原单</span>'; // 订单拆单标签
    		M('order')->where("order_id=".$order_id." and store_id =".STORE_ID)->save($res);
    		
    		M('users_price')->where('order_id='.$order_id)->save(['price'=>$result['result']['order_amount']+$result['result']['yijia_heji_s']]);
    		
           M('order_jian')->where('order_id=' . $order_id)->delete();//删除出入库重写写入记录
           
            } catch (Exception $e) {
                M()->rollback();
                // M('order_jian_debug')->add(['text'=>$e->getMessage(),'order_sn'=>$order_id,'addtime'=>time()]);
                Log::record($e->getMessage(),'editOrder');
                // echo '错误信息：'.$e->getMessage();
            }
            //编辑重写溢价统计
            //获取原单现在的商品
            $oldOrderGoods = $orderLogic->getOrderGoods($order_id);
            M('order_yijia')->where(array('order_id'=>$order_id,'store_id'=>STORE_ID))->delete();
            foreach($oldOrderGoods as $key=>$vs){
//                $goods = M('goods')->where("goods_id =".$v['goods_id'])->getField('fenbu_koudian');
                if(!empty($vs['fenbu_koudian'])){
                    $vs['fenbu_koudian'] = json_decode($vs['fenbu_koudian'],true);
                    foreach ($vs['fenbu_koudian'] as $kk=>$vv){
                        if($vv['fenbu_id'] == $order['ufenbu_id']){
                            if(!empty($vv['fenbu_koudian']) && $vv['fenbu_koudian']!=0){
                                $points = $vv['fenbu_koudian'];
                                break;
                            }
                        }
                    }
                    if(!empty($points)){
                        M('order_goods')->where('rec_id='.$vs['rec_id'])->setField(['points'=>$points]);
                        $vs['points'] = $points;
                    }
                }


                $yijia=$vs['yijia']==0 ? yj_price($vs['goods_id'],$vs['member_goods_price'],$order['fenbu_id']) : $vs['yijia'];
//                $goodsArr[$key]['price']=$yijia;
                if($yijia > 0){
                    M('order_goods')->where(['rec_id'=>$vs['rec_id']])->setField(['yijia'=>$yijia]);
                    M("order_yijia")->data([
                        'order_sn'=>$order['order_sn'],
                        'order_id'=>$order_id,
                        'goods_id'=>$vs['goods_id'],
                        'store_id'=>STORE_ID,
                        'consignee'=>$order['consignee'],
                        'spec_key'=>$vs['spec_key'],
                        'goods_num'=>$vs['goods_num'],
                        'y_price'=>$vs['member_goods_price'], //原价
                        'price'=>$yijia,
                        'fenbu_id'=>$userInfo['fenbu_id'],
                        'add_time'=>\time()
                    ])->add(); //写入溢价分成表
                }

            }

    		//################################原单处理结束

    		//################################新单处理
    		for($i=1;$i<20;$i++){
    			if(!empty($_POST[$i.'_old_goods'])){
    				$split_goods[] = $_POST[$i.'_old_goods'];//新订单商品
    			}
    		}
    		foreach ($split_goods as $key=>$vrr){
    			foreach ($vrr as $k=>$v){
    				$all_goods[$k]['goods_num'] = $v;
    				$brr[$key][] = $all_goods[$k];
    			}
    		}

    		foreach($brr as $goods){
    		    $goods[$key]['fenbu_koudian'] = M('goods')->where(['goods_id'=>$goods['goods_id']])->getField('fenbu_koudian');

    			$result = calculate_price($order['user_id'],$goods,array(STORE_ID => $order['shipping_code']),0,$order['province'],$order['city'],$order['district'],0,0,0,0,'线下',11);
    			if($result['status'] < 0)
    			{
    				$this->error($result['msg']);
    			}
    			$new_order = $order;
    			$new_order['order_sn'] = date('YmdHis').mt_rand(1000,9999);
    			$new_order['parent_sn'] = $order['order_sn'];
    			//修改订单费用
    			$new_order['goods_price']    = $result['result']['goods_price']; // 商品总价
    			$new_order['order_amount']   = $result['result']['order_amount']; // 应付金额
    			$new_order['total_amount']   = $result['result']['total_amount']; // 订单总价
				$new_order['yijia_heji']   = $result['result']['yijia_heji_s']; // 订单yijia
				$new_order['kou_price']   = $result['result']['kou_price_s']; // 订单收益
				$new_order['tag']   = '<span style="color:green">拆单新单</span>'; // 订单标签
				$new_order['jian_count']   = 0; // 订单标签数
				$new_order['ruku_count']   = 0; // 订单标签数
				$new_order['ruku_last_time']   = ''; // 订单标签数
                $new_order['pay_status']   = $order['pay_status']; // 订单支付状态
    			$new_order['add_time'] = time();
    			unset($new_order['order_id']);
    			
    			$new_order_id = M('order')->add($new_order);//插入订单表
    			M('users_price')->add(['order_id'=>$new_order_id,'user_id'=>$order['user_id'],'store_id'=>STORE_ID,'price'=>$result['result']['yijia_heji_s']+$result['result']['order_amount'],'add_time'=>time(),'status'=>0]);
    			
    			foreach ($goods as $vv){

                    if(!empty($vv['fenbu_koudian'])){
                        $vv['fenbu_koudian'] = json_decode($vv['fenbu_koudian'],true);
                        foreach ($vs['fenbu_koudian'] as $ks=>$vss){
                            if($vss['fenbu_id'] == $order['ufenbu_id']){
                                if(!empty($vss['fenbu_koudian']) && $vv['fenbu_koudian']!=0){
                                    $points = $vss['fenbu_koudian'];
                                    break;
                                }
                            }
                        }
                        if(!empty($points)){
                            M('order_goods')->where('rec_id='.$vs['rec_id'])->setField(['points'=>$points]);
                            $vv['points'] = $points;
                        }
                    }
    				$vv['order_id'] = $new_order_id;//新订单order_id
    				unset($vv['rec_id']);
                    $vv['store_id'] = STORE_ID;

    				$nid = M('order_goods')->add($vv);//插入订单商品表
                    $yijia=$vv['yijia']==0 ? yj_price($vv['goods_id'],$vv['member_goods_price'],$order['fenbu_id']) : $vv['yijia'];
                    M("order_yijia")->data([
                        'order_sn'=>$new_order['order_sn'],
                        'order_id'=>$new_order_id,
                        'goods_id'=>$vv['goods_id'],
                        'store_id'=>STORE_ID,
                        'consignee'=>$order['consignee'],
                        'spec_key'=>$vv['spec_key'],
                        'goods_num'=>$vv['goods_num'],
                        'y_price'=>$vv['member_goods_price'], //原价
                        'price'=>$yijia,
                        'fenbu_id'=>$userInfo['fenbu_id'],
                        'add_time'=>\time()
                    ])->add(); //写入溢价分成表
    			}
    		}
    		//################################新单处理结束
    		$this->success('操作成功',U('Order/detail',array('order_id'=>$order_id)));
            exit;
    	}
    	
    	foreach ($orderGoods as $val){
    		$brr[$val['rec_id']] = array('goods_num'=>$val['goods_num'],'goods_name'=>getSubstr($val['goods_name'], 0, 35).$val['spec_key_name']);
    	}

    	$this->assign('order',$order);
    	$this->assign('goods_num_arr',json_encode($brr));
    	$this->assign('orderGoods',$orderGoods);
    	$this->display();
    }
    
    /*
     * 价钱修改
     */
    public function editprice($order_id){
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $this->editable($order);
        if(IS_POST){
            $update['discount'] = I('post.discount');
            $update['shipping_price'] = I('post.shipping_price');
			$update['order_amount'] = $order['goods_price'] + $update['shipping_price'] - $update['discount'] - $order['user_money'] - $order['integral_money'] - $order['coupon_price'];
			$update['master_order_sn'] =$this->get_order_sn();
            $row = M('order')->where(array('order_id'=>$order_id,'store_id'=>STORE_ID))->save($update);
            if(!$row){
                $this->success('没有更新数据',U('Order/editprice',array('order_id'=>$order_id)));
            }else{
                $this->success('操作成功',U('Order/detail',array('order_id'=>$order_id)));
            }
            exit;
        }
        $this->assign('order',$order);
        $this->display();
    }
   /**
    * 获取订单 order_sn
    */
   public function get_order_sn()
   {
		// 保证不会有重复订单号存在
		while(true){
			$order_sn = date('YmdHis').rand(1000,9999); // 订单编号
			$order_sn_count = M('order')->where("order_sn = '$order_sn' or master_order_sn = '$order_sn'")->count();
			if($order_sn_count == 0)
				break;
		}
		return $order_sn;
   }
    /**
     * 订单删除
     * @param int $id 订单id
     *  store_id   
     */
    public function delete_order($order_id){
    	$orderLogic = new OrderLogic();
    	$del = $orderLogic->delOrder($order_id,STORE_ID);
        if($del){
            $this->success('删除订单成功');
        }else{
        	$this->error('订单删除失败');
        }
    }
    
    /**
     * 订单取消付款
     */
    public function pay_cancel($order_id){
    	if(I('remark')){
    		$data = I('post.');
    		$note = array('退款到用户余额','已通过其他方式退款','不处理，误操作项');
    		if($data['refundType'] == 0 && $data['amount']>0){
    			accountLog($data['user_id'], $data['amount'], 0,  '退款到用户余额');
    		}
    		$orderLogic = new OrderLogic();
            $orderLogic->orderProcessHandle($data['order_id'],'pay_cancel');
            $order = $orderLogic->getOrderInfo($data['order_id']);
			$seller_id = session('seller_id');			
    		$d = $orderLogic->orderActionLog($order,'取消付款',$data['remark'].':'.$note[$data['refundType']],$seller_id,1);
    		if($d){
    			exit("<script>window.parent.pay_callback(1);</script>");
    		}else{
    			exit("<script>window.parent.pay_callback(0);</script>");
    		}
    	}else{
    		$order = M('order')->where("order_id=$order_id")->find();
    		$this->assign('order',$order);
    		$this->display();
    	}
    }

    /**
     * 订单打印
     * @param int $id 订单id 
     */
    public function order_print(){
    	$order_id = I('order_id');
        $orderLogic = new OrderLogic(); 
		
		$action=trim(I('action'));
		if($action=="yes" && $order_id!=''){
		    if(I('type') == 'dayin_biaoqian'){
                M('order')->where('order_id in('.$order_id.')')->setInc('dayin_biaoqian');
            }else{
                M('order')->where('order_id in('.$order_id.')')->setInc('dayin_store');
                M('order')->where('order_id in('.$order_id.')')->save(['dayin_time'=>time()]);
            }
			exit;
		}else if($action=="jishu" && $order_id!=''){
            if(I('type') == 'dayin_biaoqian'){
                $jishu=M('order')->where('order_id in('.$order_id.')')->sum('dayin_biaoqian');
            }else{
                $jishu=M('order')->where('order_id in('.$order_id.')')->sum('dayin_store');
            }
			echo $jishu;
			exit;
		}
		
        $order = $orderLogic->getOrderInfo($order_id);
        // dump($order);
        $mobile_staus = M('store')->where(['store_id'=>STORE_ID])->getField('mobile_staus');
        if($mobile_staus == 0){
            $order['mobile'] = '***********';
        }
        // dump($order);

		if(empty($order) || empty($order_id))
			$this->error('非法操作！');
        $fast_flag = M('users')->where("user_id=".$order['user_id'])->getField('fast_flag');
        $fast_flag2 = M('store')->where("store_id=".$order['store_id'])->getField('fast_flag');
        if($fast_flag && $fast_flag2){
            $fast_text = '快';
        }else{
            $fast_text = '';
        }
        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        // if(session('super') != 'shadow'){
        //     $order['mobile'] = '***********';
        // }
        $order['full_address'] = $order['province'].' '.$order['city'].' '.$order['district'].' '. $order['address'];
        
        
        
        
        // 获取店铺活动
        $activity = M('goods_full')->where([
            'store_id' => STORE_ID,
            'start_time' => ['elt', time()],
            'end_time' => ['egt', time()]
        ])->order('id desc')->find();
        // dump($activity);
        if ($activity) {
            
            $where = [];
            if(!empty($activity['brand_id'])){
                $brand_id = implode(',',json_decode($activity['brand_id'],true));
     
                $where['gs.store_cat_id1'] = ['in',$brand_id];
            }
             if(!empty($activity['goods_id'])){
                $goods_id = implode(',',json_decode($activity['goods_id'],true));
  
                $where['gs.goods_id'] = ['in',$goods_id];
            }
            // 获取当天用户下单总金额
             if($activity['type'] == 1){
                // 获取当天用户下单总金额

                $todayStart = strtotime('midnight', $order['add_time']);
                $todayEnd = strtotime('tomorrow', $order['add_time']) - 1;
            }else{
                // dump(123);
                // 获取这个时间区间的
                $todayStart = $activity['start_time'];
                $todayEnd = $activity['end_time'];
            }  

            $where['o.user_id'] = $order['user_id'];
            $where['o.order_status'] = ['in','0,1,2'];
            $where['o.store_id'] = STORE_ID;
            $where['o.add_time'] = ['between', [$todayStart, $todayEnd]];
            // dump($where);
            $totalAmount = M('order_goods g')
    	    ->join('ty_order o on o.order_id = g.order_id','left')
    	    ->join('ty_goods gs on gs.goods_id = g.goods_id','left')
//                ->fetchSql()
    	    ->where($where)->sum('(g.member_goods_price+g.yijia)*goods_num');
//            var_dump($order);exit;
            // dump($totalAmount);
            if(empty($totalAmount)){
                $totalAmount = 0;
            }
            // dump($totalAmount);
            // 判断是否达到活动条件
            $finalGift = null;
            $gifts = json_decode($activity['full_gift'], true);
            usort($gifts, function($a, $b) {
                return $b['price'] <=> $a['price'];
            });
            foreach ($gifts as $gift) {
                if ($totalAmount >= $gift['price']) {
                    $finalGift = '满'.$gift['price'].'元赠'.$gift['gift'];
                    break;
                }
            }

            if($finalGift){
                $order['user_note'] = $order['user_note'].'('.$activity['name'].'赠品：'.$finalGift.')';
            }
            
        }

        $orderGoods = $orderLogic->getOrderGoods($order_id);
        // dump($orderGoods);
        $koudian  = 0;
        foreach ($orderGoods as $k=>$v){
            $orderGoods[$k]['spec_key_name'] = str_replace('颜色:','',$v['spec_key_name']);
            $orderGoods[$k]['spec_key_name'] = str_replace('包装:','',$v['spec_key_name']);
            $orderGoods[$k]['spec_key_name'] = str_replace('规格:','',$orderGoods[$k]['spec_key_name']);
            $koudian += (($v['points']/100)*$v['member_goods_price'])*$v['goods_num'];
            if($v['prom_id'] != 0){
                $prom = M('prom_goods')->where(['id'=>$v['prom_id']])->find();
                if(time() > $prom['start_time'] && time() < $prom['end_time']){
                    $orderGoods[$k]['huodong'] = '(活动商品)';
                }
            }
            if($v['prom_type'] == 4 ){
                //查看满赠活动多送
                $goodsfull = M('prom_goods')->where(['id'=>$v['prom_id']])->find();

                if($goodsfull['type'] == 4){
                    $goods_key = json_decode($goodsfull['goods_key'],true);
                    $full = explode('/',$goodsfull['expression']);
                    $goodsfull['goods_num'] = $full[0];
                    $goodsfull['send_num'] = $full[1];
                    if(in_array($v['spec_key'],$goods_key)){
                        $msg = '满'.$goodsfull['goods_num'].'送'.$goodsfull['send_num'];
                        //存在这个满赠活动多送的情况先，修改order_goods
                        $freeQuantity = floor(floatval($v['goods_num']) / $goodsfull['goods_num']) * $goodsfull['send_num'];// 计算赠送商品数量，使用 floor 函数取整数部分
                        if($freeQuantity > 0){
                            // $orderGoods[$k]['goods_num'] = floatval($v['goods_num']).'+'.$freeQuantity;
                            // $orderGoods[$k]['goods_name'] = $v['goods_name'].'('.$msg.')';
                            // 获取 DRIVER_SET 数组最后一个键
                            $lastKey = end(array_keys($orderGoods));
                            // 解析最后一个键的数字部分
                            $lastNumber = (int) substr($lastKey, 2);
                            // 生成新的键
                            $newKey = sprintf('%03d', $lastNumber + 1);
                            // 复制最后一行数据
                            $newData = $orderGoods[$k];
                            // 将复制的数据添加到 DRIVER_SET 数组末尾
                            $newData['goods_num'] = $freeQuantity;
                            $newData['goods_name'] = $v['goods_name'].'('.$msg.')';
                            $newData['goods_kou_price'] = 0;
                            $newData['goods_kou_total'] = 0;
                            $orderGoods[$newKey] = $newData;
                        }


                    }
                }
            }
        }
        $order['kou_price'] = $koudian;
        $order['total_amount'] =  sanwei($order['total_amount']);
        $store = M('store')->where("store_id=".STORE_ID)->find();
       if($store['phone_status'] == 0){
            $order['mobile'] = '********'; 
            if(!empty($store['store_phone'])){
                $store['store_phone'] = '********';
            }
        }
        // dump($order);
        $shop = tpCache('shop_info');
        $this->assign('order',$order);
		$this->assign('users',M('users')->where("user_id=".$order['user_id'])->find());
		update_user_level($order['user_id']);
        $this->assign('shop',$shop);
        $this->assign('fast_text',$fast_text);
        $this->assign('store',$store);
        $this->assign('orderGoods',$orderGoods);
        $template = I('template','print');
        $this->display($template);
    }

    /**
     * 快递单打印
     */
    public function shipping_print(){
        $order_id = I('get.order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        //查询是否存在订单及物流
        $shipping = M('plugin')->where(array('code'=>$order['shipping_code'],'type'=>'shipping'))->find();        
        if(!$shipping){
        	$this->error('物流插件不存在');
        }
		if(empty($shipping['config_value'])){
			$this->error('请联系平台管理员设置'.$shipping['name'].'打印模板');
		}
        $shop = M('store')->where(array('store_id'=>STORE_ID))->find();
        $shop['province'] = empty($shop['province_id']) ? '' : getRegionName($shop['province_id']);
        $shop['city'] = empty($shop['city_id']) ? '' : getRegionName($shop['city_id']);
        $shop['district'] = empty($shop['district']) ? '' : getRegionName($shop['district']);

        $order['province'] = getRegionName($order['province']);
        $order['city'] = getRegionName($order['city']);
        $order['district'] = getRegionName($order['district']);
        if(empty($shipping['config'])){
        	$config = array('width'=>840,'height'=>480,'offset_x'=>0,'offset_y'=>0);
        	$this->assign('config',$config);
        }else{
        	$this->assign('config',unserialize($shipping['config']));
        }
        $template_var = array("发货点-名称", "发货点-联系人", "发货点-电话", "发货点-省份", "发货点-城市",
        		 "发货点-区县", "发货点-手机", "发货点-详细地址", "收件人-姓名", "收件人-手机", "收件人-电话", 
        		"收件人-省份", "收件人-城市", "收件人-区县", "收件人-邮编", "收件人-详细地址", "时间-年", "时间-月", 
        		"时间-日","时间-当前日期","订单-订单号", "订单-备注","订单-配送费用");
        $content_var = array($shop['store_name'],$shop['seller_name'],$shop['store_phone'],$shop['province'],$shop['city'],
        	$shop['district'],$shop['store_phone'],$shop['store_address'],$order['consignee'],$order['mobile'],$order['phone'],
        	$order['province'],$order['city'],$order['district'],$order['zipcode'],$order['address'],date('Y'),date('M'),
        	date('d'),date('Y-m-d'),$order['order_sn'],$order['admin_note'],$order['shipping_price'],
        );
        $shipping['config_value'] = str_replace($template_var,$content_var, $shipping['config_value']);
        $this->assign('shipping',$shipping);
        $this->display("Plugin/print_express");
    } 

    /**
     * 标签打印shadow
     * @param int $id 订单id
     */
    public function biaoqian_print(){
    	$order_id = I('order_id');
		$order=M('order a') 
		->field('a.*,b.store_name,c.biaoshi_xian,c.biaoshi,c.fast_flag,b.biaoqian_print,b.printb_w,b.printb_h,c.company,a.order_status,c.nickname')
		->join('ty_store b on a.store_id=b.store_id','left')
		->join('ty_users c on a.user_id=c.user_id','left')
		->where('order_id='.$order_id)->find();
        
        
        if($order['order_status'] == 3 || $order['order_status'] == 5){
            $this->error('此单已取消或作废！');
        }
        
		$pic_data=[];
        if($order['jian_count'] <=150){
            for($i=1;$i<=(int)$order['jian_count'];$i++){
                $erwei=$this->mypng($order_id,$i,1); //0条码，1二维码
                $pic_data[$i]=\pic64($erwei);
            }
            $fast_flag = M('users')->where("user_id=".$order['user_id'])->getField('fast_flag');
            $fast_flag2 = M('store')->where("store_id=".$order['store_id'])->getField('fast_flag');
            if($fast_flag && $fast_flag2){
                $order['fast_text'] = '快';
            }else{
                $order['fast_text'] = '';
            }
            $order['company'] = $order['company'].'('.$order['nickname'].')';
            $this->assign('order',$order);
            $this->assign('myfenbu_name',M('fenbu')->where('fenbu_id='.$order['ufenbu_id'])->getField('fenbu_name'));
            $this->assign('pic_data1',$pic_data[1]);
            $this->assign('pic_data',\json_encode($pic_data));
        }

        $this->display();
    }
	
	public function mypng($order_id,$jian,$type=1){
		$mydata = \json_encode([
			(int)$order_id,$jian
		]);
		$picname=\md5($mydata);
		$date = date('Y-m-d',time());
		if($type==1){
			$filename = '/Public/goodsqrcode/erwei/'.$date.'/'.$picname.'.png';
			$filename2 = './Public/goodsqrcode/erwei/'.$date;
			if(!file_exists($filename2)){
                $a = mkdir($filename2, 0777, true);
            }
		    Vendor('phpqrcode.phpqrcode');
		    $object = new \QRcode();
		    $level = 'Q'; //容错级别 分为L、M、Q、H
		    $size = 6; //点的大小 1~10,手机端用4即可

			    if (!file_exists($filename)) {
			        $object->png($mydata,'.'.$filename,$level,$size);
			    }
		}else{
			$filename = './Public/goodsqrcode/erwei/'.$date.'/'.$picname.'.png';
            $filename2 = '/Public/goodsqrcode/erwei/'.$date;
            if(!file_exists($filename2)){
                mkdir($filename2, 0777, true);
            }
			$font = new BCGFontFile('./ThinkPHP/Library/Vendor/yiwei/font/Arial.ttf', 18);
			$color_black = new BCGColor(0, 0, 0);
			$color_white = new BCGColor(255, 255, 255);
			$drawException = null;
			try {
				$code = new BCGcode128();
				$code->setScale(2); // Resolution
				$code->setThickness(30); // Thickness
				$code->setForegroundColor($color_black); // Color of bars
				$code->setBackgroundColor($color_white); // Color of spaces
				$code->setFont(0); // Font (or 0)
				$code->setStart(null);
				$code->setTilde(true);
				$code->parse($mydata); // Text
			} catch (Exception $exception) {
				$drawException = $exception;
			}
		if (!file_exists($filename)) {
			$drawing = new BCGDrawing('', $color_white);
				$drawing->setBarcode($code);
				$drawing->setFilename($filename);
				$drawing->draw();
			$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
		}
		}
		$picurl=SITE_URL.$filename;
		return $picurl;
	}
    /**
     * 生成发货单
     */
    public function deliveryHandle(){
        $orderLogic = new OrderLogic();
		$data = I('post.');//echo \json_encode($data);exit;
		$res = $orderLogic->deliveryHandle($data,STORE_ID);
		if($res){
			$this->success('操作成功',U('Order/delivery_info',array('order_id'=>$data['order_id'])));
		}else{
			$this->success('操作失败',U('Order/delivery_info',array('order_id'=>$data['order_id'])));
		}
    }

    
    public function delivery_info(){
    	$order_id = I('order_id');
    	$orderLogic = new OrderLogic();
    	$order = $orderLogic->getOrderInfo($order_id);
    	$orderGoods = $orderLogic->getOrderGoods($order_id);
		$delivery_record = M('delivery_doc')->join('LEFT JOIN __SELLER__ ON __SELLER__.seller_id = __DELIVERY_DOC__.admin_id')->where('order_id='.$order_id)->select();
		if($delivery_record){
			$order['invoice_no'] = $delivery_record[count($delivery_record)-1]['invoice_no'];
		}
		$this->assign('order',$order);
		$this->assign('orderGoods',$orderGoods);
		$this->assign('delivery_record',$delivery_record);//发货记录
    	$this->display();
    }
    
    /**
     * 发货单列表
     */
    public function delivery_list(){
        $this->display();
    }
    /**
     * 退货单列表
     */
    public function return_list(){
    	$begin = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
    	$end = date('Y-m-d 23:59',strtotime('+1 days')); 	
    	$this->assign('timegap',$begin.' - '.$end);
        $this->display();
    }	
    /*
     * ajax 退货订单列表
     */
    public function ajax_return_list(){
		 $orderLogic = new OrderLogic();
		 $timegap = I('timegap');
		 if($timegap){ 
			$gap = explode(' - ', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
		 }
		 // 搜索条件 STORE_ID 
		 $condition = array('a.store_id'=>STORE_ID); // 商家id 
		 I('consignee') ? $condition['consignee'] = array('like','%'.trim(I('consignee')).'%'): false;
		 if($begin && $end){
			$condition['add_time'] = array('between',"$begin,$end");
		 }
		 I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
		 I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
		 I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
		 I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
		 I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
		 $condition['admin_note'] = ['neq',''];
		 //$condition['order_prom_type'] = 0;
		 $condition['master_order_sn'] = ['neq',''];
		 
		 //$sort_order = I('order_by','DESC').' '.I('sort');
		 $sort_order = 'order_id DESC';
		 $count = M('order a')
		 ->field('a.*,b.goods_name')
		 ->join('ty_order_goods b on a.order_id=b.order_id')
		 ->group('a.order_id')
		 ->where($condition)->count();
		 $Page  = new AjaxPage($count,20);
		 $show = $Page->show();
		 //获取订单列表
		 $orderList = $orderLogic->getOrderList($condition,$sort_order,$Page->firstRow,$Page->listRows);
		 //获取主订单号
		 
		 foreach($orderList as $key=>$value){
			//去重复
			$goods = M('order_goods a')->field('a.*,b.original_img')
			->join('ty_goods b ON a.goods_id = b.goods_id')
			->where(array('a.order_id'=>$value['order_id']))
			->select();
		 
			$orderList[$key]["ruku"]=M('order_jian')->where('order_id='.$value['order_id'].' and status_r=1')->count();
			$orderList[$key]["chuku"]=M('order_jian')->where('order_id='.$value['order_id'].' and status_c=1')->count();
			$orderList[$key]["biaoqian"]=$orderList[$key]["ruku"]!='0'? 'disabled="disabled"':'';
			$orderList[$key]["company"]=M('users')->where('user_id='.$value['user_id'])->getField('company');
			
			$orderList[$key]["g_list"]=$goods;
			
			$orderList[$key]["pay_name"]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$value['pay_code']))->getField('name');
			
		 }
		 
		 $this->assign('orderList',$orderList);
		 $this->assign('page',$show);// 赋值分页输出
		 $this->display();
    }
    
    /**
     * 删除某个退换货申请
     */
    public function return_del(){
        $id = I('get.id');
        M('return_goods')->where("id = $id and store_id = ".STORE_ID)->delete(); 
        $this->success('成功删除!');
    }
    /**
     * 退换货操作
     */
    public function return_info()
    {
        $id = I('id');
        $return_goods = M('return_goods')->where("id= $id  and store_id = ".STORE_ID)->find();
        empty($return_goods) && $this->error("参数有误");


        if($return_goods['imgs'])      {
           $return_goods['imgs']=json_decode($return_goods['imgs']);
        }
        foreach ($return_goods['imgs'] as $k =>$v){
            $return_goods['imgs'][$k] = SITE_URL.$v;
        }

        $user = M('users')->where("user_id = {$return_goods[user_id]}")->find();
        $goods = M('goods')->where("goods_id = {$return_goods[goods_id]}")->find();
        $order_goods = M('order_goods')->where("order_id ={$return_goods['order_id']} and goods_id = {$return_goods['goods_id']} and spec_key = '{$return_goods['spec_key']}'")->find();

        $type_msg = array('退款退货','换货');

        $status_msg = array('未处理','处理中','已完成');
        if(IS_POST)
        {            
            $data['status'] = I('status');
            $data['remark'] = I('remark');                                    
            $note ="退换货:{$type_msg[$return_goods['type']]}, 状态:{$status_msg[$data['status']]},处理备注：{$data['remark']}";
            $result = M('return_goods')->where("id= $id  and store_id = ".STORE_ID)->save($data);    
            if($result)
            {                    	
                // 如果是换货
                if($return_goods['type'] == 1)
                {
                    $where = " order_id = ".$return_goods['order_id']." and goods_id=".$return_goods['goods_id'];
                    M('order_goods')->where($where)->save(array('is_send'=>2));//更改商品状态                           
                }
                $orderLogic = new OrderLogic();
                $seller_id = session('seller_id');
                $order = $orderLogic->getOrderInfo($return_goods['order_id']);

                $log = $orderLogic->orderActionLog($order,"{$type_msg[$return_goods['type']]}",$note,$seller_id,1);

                $this->success('修改成功!');            
                exit;
            }  
        }        
        
        $this->assign('id',$id); // 用户
        $this->assign('user',$user); // 用户
        $this->assign('goods',$goods);// 商品        
        $this->assign('order_goods',$order_goods);// 商品列表
        $this->assign('return_goods',$return_goods);// 退换货               
        $this->display();
    }
    
    /**
     * 管理员生成申请退货单
     */
    public function add_return_goods()
   {                
            $order_id = I('order_id'); 
            $goods_id = I('goods_id');
                
            $return_goods = M('return_goods')->where("order_id = $order_id and goods_id = $goods_id")->find();            
            if(!empty($return_goods))
            {
                $this->error('已经提交过退货申请!',U('Admin/Order/return_list'));
                exit;
            }
            $order = M('order')->where("order_id = $order_id")->find();
            
            $data['order_id'] = $order_id; 
            $data['order_sn'] = $order['order_sn']; 
            $data['goods_id'] = $goods_id; 
            $data['addtime'] = time(); 
            $data['user_id'] = $order[user_id];            
            $data['remark'] = '管理员申请退换货'; // 问题描述            
            M('return_goods')->add($data);            
            $this->success('申请成功,现在去处理退货',U('Admin/Order/return_list'));
            exit;
    }

    /**
     * 订单批量操作shadow
     * @param $id
     */
    public function order_actions(){
        $orderLogic = new OrderLogic();
        $action = $_POST['type'];
        $order_id = $_POST['order_ids'];
		$text=$_POST['reason'];
		if($order_id){
			$order_id=\explode(',',$order_id);
		}else{exit;}
		if($action=='confirm' || $action=='invalid' || $action=='cancel'){
		    
			foreach($order_id as $v){
				$orderLogic->orderProcessHandle($v,$action,STORE_ID);
			}
			echo '0';
		}elseif($action=='fahuo'){
			$goods=[];$mypost=[];
			foreach($order_id as $v){
				$mypost['goods']=M('order_goods')->where('order_id='.$v)->getField('rec_id',true);
				$mypost['order_id']=$v;
				$mypost['note']=$text;
				$orderLogic->orderProcessHandle($v,'confirm',STORE_ID); //确定
				$orderLogic->deliveryHandle($mypost,STORE_ID); //发货
			}
			echo '0';
		}elseif($action=='hebing'){
            if(\count($order_id)<=1){
                echo '-2';exit;
            }

            $new_order_id=$old_order_id="";$new_amount=0;
            foreach($order_id as $key=>$v){
                if($key==0){
                    $new_order_id=$v;
                }else{
                    $old_order_id.=$v.',';
                }
            }
            $old_order_id=substr($old_order_id,0,strlen($old_order_id)-1);


            $order_list=M('order')->where('order_id in('.$old_order_id.') and order_status=0')->select();
            foreach ($order_list as $k=>$v){
                if($v['coupon_price'] > 0){
                     echo '-2';exit;
                }
                if($v['stock_up'] == 2){
                     echo '-2';exit;
                }
            }
            
            $order_pd=M('order')->field('user_id,pay_status,order_sn,ufenbu_id')->where('order_id='.$new_order_id.' and order_status=0')->find();

            //判断是否是同一个收货人。
            foreach($order_list as $v){
                if($order_pd['user_id']!=$v['user_id']){
                    echo '-1';exit;
                }
                if($order_pd['pay_status']!=$v['pay_status']){
                    echo '-1';exit;
                }
                $hborder_sn.=substr($v['order_sn'],-8).'<-';
            }
            $userInfo = M('users')->where(['user_id'=>$v['user_id']])->find();
            sellerLog('合并订单：'.$hborder_sn);

            if($order_list){
                M('order_goods')->where('order_id in('.$old_order_id.')')->save([
                    'order_id'=>$new_order_id
                ]);

                M('order')->where('order_id in('.$old_order_id.')')->delete(); //删除多余主单
                M('users_price')->where('order_id in('.$old_order_id.')')->delete();

                //by sofwu 解决合并订单相同产品相同规格不合并数量的问题   start
                $data = M('order_goods')->where(['order_id'=>$new_order_id])->select();
                $result = array();
                foreach($data as $val){
                    $key = $val['spec_key'];
                    if(!isset($result[$key])){
                        $result[$key] = $val;
                    }else{
                        $result[$key]['goods_num'] += $val['goods_num'];
                    }
                }

                $result = array_values($result);
                if($result){
                    M('order_goods')->where(['order_id'=>$new_order_id])->delete();
                    foreach ($result as $item){
                        M('order_goods')->add($item);
                    }
                }
                //by sofwu 解决合并订单相同产品相同规格不合并数量的问题   end


                //新旧orderyijia一起删除重新写入
                M('order_yijia')
                    ->where('order_id in('.$old_order_id.')')
                    ->where(array('store_id'=>STORE_ID))
                    ->delete();
                M('order_yijia')
                    ->where(array('order_id'=>$new_order_id,'store_id'=>STORE_ID))
                    ->delete();
                $order_goods=M('order_goods')->where('order_id='.$new_order_id)->select();//获取新主单产品
                foreach($order_goods as $v){ //计算单据产品价格
                    //算出分部扣点
                    $fenbu_koudian = M('goods')->where("goods_id =".$v['goods_id'])->getField('fenbu_koudian');
                    if(!empty($fenbu_koudian)){
                        $fenbu_koudian = json_decode($fenbu_koudian,true);
                        // $goods['points'] = 0;
                        $break = 0;
                        foreach ($fenbu_koudian as $kk=>$vv){
                            if($vv['fenbu_id'] == $order_pd['ufenbu_id']){
                                if(!empty($vv['fenbu_koudian']) && $vv['fenbu_koudian'] !=0){
                                    $v['points'] = $vv['fenbu_koudian'];
                                    $break = 1;
                                    break;
                                }
                            }
                        }
                        if($v['points'] != 0 && $break = 1){
                            M('order_goods')->where('rec_id='.$v['rec_id'])->setField(['points'=>$v['points']]);
                        }
                    }


                    $new_kou += sanwei($v['goods_price']*$v['goods_num'] *$v['points']/100);
                    $new_amount+=$v['member_goods_price']*$v['goods_num'];
                    //计算溢价
                    $yijias += (yj_price($v['goods_id'],$v['member_goods_price'],$userInfo['fenbu_id']))*$v['goods_num'];
                    $yijia=$v['yijia']==0 ? yj_price($v['goods_id'],$v['member_goods_price'],$userInfo['fenbu_id']) : $v['yijia'];
                    if($yijia > 0){
                        M('order_goods')->where(['rec_id'=>$v['rec_id']])->setField(['yijia'=>$yijia]);
                       M("order_yijia")->data([
                            'order_sn'=>$order_pd['order_sn'],
                            'order_id'=>$new_order_id,
                            'goods_id'=>$v['goods_id'],
                            'store_id'=>STORE_ID,
                            'consignee'=>$userInfo['nickname'],
                            'spec_key'=>$v['spec_key'],
                            'goods_num'=>$v['goods_num'],
                            'y_price'=>$v['member_goods_price'], //原价
                            'price'=>$yijia,
                            'fenbu_id'=>$userInfo['fenbu_id'],
                            'add_time'=>\time()
                        ])->add(); //写入溢价分成表 
                    }
                    
                }
                M('users_price')->where('order_id='.$new_order_id)->save(['price'=>$new_amount+$yijias]);
                M('order')->where('order_id='.$new_order_id)->save([
                    'goods_price'=>$new_amount,
                    'order_amount'=>$new_amount,
                    'total_amount'=>$new_amount,
                    'yijia_heji' =>$yijias,
                    'kou_price' =>$new_kou,
                    'tag'=>'<span style="color:#f88e2d">合并订单</span>'
                ]);
            }
            echo '0';

		}
    }
	
	

    /**
     * 订单操作
     * @param $id
     */
    public function order_action(){
        $orderLogic = new OrderLogic();
        $action = I('get.type');
        $order_id = I('get.order_id');

        $store_id = I('get.store_id');
        $goods_id = I('get.goods_id');
        $spec_key = I('get.spec_key');

        //获取订单id和操作类型
        if($action && $order_id){
            //改变订单状态
        	 $a = $orderLogic->orderProcessHandle($order_id,$action,STORE_ID);
			 $seller_id = session('seller_id');
             //获取订单信息
			 $order = $orderLogic->getOrderInfo($order_id);
            //获取这个订单的所有商品
//            $order_goods = M('order_goods')->where("order_id ={$order['order_id']} and goods_id = {$goods_id} and store_id = {$store_id} and spec_key = '{$spec_key}'")->find();
            $order_goods = M('order_goods')->where("order_id ={$order['order_id']}")->find();

			 //订单已支付后操作作废订单
			 if ($action == 'invalid' && $order['pay_status']=1 && $order_goods['is_send'] == 0){

//                     $refund = order_settlement($order_id,$order_goods['rec_id']);  // 查看退款金额
                     $refund = order_settlement($order_id,0);  // 查看退款金额

                 $return_goods_price = $refund[0]['store_settlement'] ? $refund[0]['store_settlement'] : 0; // 这个商品的退款金额

                 $refund_integral = $refund[0]['integral'] - $refund[0]['give_integral'];

//                 $pending_money = M('store')->where(" store_id = ".STORE_ID)->getField('pending_money'); // 商家未结算资金
//                 if($pending_money < $return_goods_price)
//                     $this->error("你的未结算资金不足 ￥{$return_goods_price}");

                 //根据订单提交的方式进行退款
                   if($order['pay_code'] == 'balance'){
                       //从商家未结算资金中扣钱，并且记录商家账户日志
                       $result = storeAccountLog(STORE_ID,0,$return_goods_price * -1,'退款',$order_goods['order_id']);
                       //客户支付方式为余额支付
                           accountLog($order['user_id'],$return_goods_price,$refund_integral,'订单退款',0,$order_goods['order_id']);

                   }else{
                       //客户支付方式为微信支付

                    $order_id = $order['order_id'];
                    $order_sn = $order['master_order_sn'];
                    $money_paid =$order['total_amount'];

                    require_once('/plugins/payment/weixin/wxrefund.php');
                    require_once('/plugins/payment/weixin/lib/WxPay.Api.php');

                    $wx_refund_status=do_wx_refund($order_id,$order_sn,$money_paid,$return_goods_price);
                     if ($wx_refund_status){
                         echo 'success';
                     }

                   }

                  //如果一笔订单中 有退货情况, 整个分销也取消
                 M('rebate_log')->where("order_id = {$order_goods['order_id']}")->save(array('status'=>4,'remark'=>'订单有退款取消分成'));

             }
             //记录订单操作日志
                if(session('super') == 'shadow'){
                    $seller_id = 0;
                    $user_type = 0;
                }else{
                    $user_type = 1;
                }

        	 $res = $orderLogic->orderActionLog($order,$action,I('note'),$seller_id,$user_type);

        	 if($res ){

        	 	exit(json_encode(array('status' => 1,'msg' => '操作成功')));
        	 }else{
        	 	exit(json_encode(array('status' => 0,'msg' => '操作失败')));
        	 }
        }else{
        	$this->error('参数错误',U('Admin/Order/detail',array('order_id'=>$order_id)));
        }
    }
    
    public function order_log(){
    	$timegap = I('timegap');
    	if($timegap){
    		$gap = explode(' - ', $timegap);
    		$begin = strtotime($gap[0]);
    		$end = strtotime($gap[1]);
    	}
    	$condition = array();
    	$log =  M('order_action');
    	if($begin && $end){
    		$condition['log_time'] = array('between',"$begin,$end");
    	}
    	$admin_id = I('admin_id');
		if($admin_id >0 ){
			$condition['action_user'] = $admin_id;
		}
		$condition['store_id'] = STORE_ID;
    	$count = $log->where($condition)->count();
    	$Page = new \Think\Page($count,20);
    	foreach($condition as $key=>$val) {
    		$Page->parameter[$key] = urlencode($val);
    	}
    	$show = $Page->show();
    	$list = $log->where($condition)->order('action_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
    	$this->assign('list',$list);
    	$this->assign('page',$show);   	
    	$seller = M('seller')->getField('seller_id,seller_name');
    	$this->assign('admin',$seller);    	
    	$this->display();
    }

    /**
     * 检测订单是否可以编辑
     * @param $order
     */
    private function editable($order){
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
        return;
    }

    public function export_order()
    {
    	//搜索条件
    //     $timegap = I('timegap');
    //             if($timegap){
    //             	$gap = explode(' - ', $timegap);
    //             	$begin = strtotime($gap[0]);
    //             	$end = strtotime($gap[1]);
    //             }
    //             // 搜索条件 STORE_ID
    //             $condition = array('a.store_id'=>STORE_ID); // 商家id 
    //             //I('consignee') ? $condition['consignee'] = array('like','%'.trim(I('consignee')).'%'): false;
    //             if($begin && $end){
    //             	$condition['add_time'] = array('between',"$begin,$end");
    //             }
    //             I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") ';
    //             I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
    //             I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
				
				// if(I('order_status') == '35'){
				// 	$condition['order_status'] = array('in','3,5');
				// }elseif(I('order_status') != ''){
				// 	$condition['order_status'] = I('order_status');
				// }
				
    //             $condition['order_prom_type'] = 0;
                
            $timegap = I('timegap');
        if($timegap){
        	$gap = explode(' - ', $timegap);
        	$begin = strtotime($gap[0]);
        	$end = strtotime($gap[1]);
        }
        // 搜索条件 STORE_ID
        $condition = array('a.store_id'=>STORE_ID); // 商家id
		I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") OR (a.mobile like "%'.I('consignee').'%")';
		I('goods_name') ? $condition['goods_name'] = array('like','%'.trim(I('goods_name')).'%'): false;
        if($begin && $end){
        	$condition['add_time'] = array('between',"$begin,$end");
        }
        I('goods_name') ? $condition['goods_name'] = array('like','%'.trim(I('goods_name')).'%'): false;
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        //I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
		if(I('order_status') == '3'){
			$condition['order_status'] = array('in','3,5');
		}elseif(I('order_status') != ''){
			$condition['order_status'] = I('order_status');
		}
		if(I('order_status') == 99){
		    $condition['order_status'] = array('not in','3,5');
		}
        //$condition['order_prom_type'] = 0;
        I('fast_flag') != '' ? $condition['c.fast_flag'] = I('fast_flag') : false;
        I('biaoshi_xian') != '' ? $condition['biaoshi_xian'] = ['like',"%".I('biaoshi_xian')."%"] : false;    
                
                

        //获取订单列表
//         $orderList = M('order a')
// 		->field('a.*,c.company,c.company_address,c.mobile,c.fast_flag')
// 		->join('ty_users c on a.user_id=c.user_id','LEFT')
// 		->group('a.order_id')
// 		->where($condition)->order('order_id desc')->select();
		$orderList = M('order a')
		->field('a.*,c.company,c.company_address,c.mobile,c.fast_flag,c.biaoshi_xian,c.user_id')
		->join('ty_order_goods b on a.order_id=b.order_id','LEFT')
		->join('ty_users c on a.user_id=c.user_id','LEFT')
		->group('a.order_id')
		->where($condition)->select();
		//echo \json_encode($condition);exit;
		
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">包装件数</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">店铺-收货人</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户id</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">线路</td>';
    	//$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
    	//$strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">供应价</td>';
		//$strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">应收金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单状态</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">是否快线</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
    	$strTable .= '</tr>';
    	

    	foreach($orderList as $k=>$val){
		$tuihuo=M('return_goods')->where('order_id='.$val['order_id'])->select();$tuihuos=$tuihuo0=0;
			foreach($tuihuo as $vs){
				$tuihuo0+=\sanwei($vs['member_goods_price']*$vs['goods_num']);
				$tuihuos+=\sanwei($vs['member_goods_price']-($vs['member_goods_price']*$vs['points']/100));
			}
		
		$orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
		$koudian=0;$koudians=0;$order_status="";
		
		if($val['order_status']==0){
			$order_status="<span style='color:red'>未发货</span>";
		}elseif($val['order_status']==1){
			$order_status="<span style='color:blue'>已发货</span>";
		}elseif($val['order_status']==2){
			$order_status="<span style='color:green'>完成</span>";
		}else{
			$order_status="作废/取消";
		}
		if($val['fast_flag'] == 1){
		    $fast_flag = '快';
		}else{
		    $fast_flag = '否';
		}
		foreach($orderGoods as $goods){
			$koudian+=\sanwei($goods['member_goods_price']*$goods['goods_num']*$goods['points']/100);
			$koudians+=\sanwei(($goods['member_goods_price']*$goods['goods_num']) - ($goods['member_goods_price']*$goods['goods_num']*$goods['points']/100));
		}
		
		unset($orderGoods);
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['jian_count'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['company'].' - '.$val['consignee'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['user_id'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['biaoshi_xian'].'</td>';
            //$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['address'].' </td>';
            //$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['total_amount'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['total_amount'].'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$koudian.'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$koudians.'</td>';
			//$strTable .= '<td style="text-align:left;font-size:12px;">'.$tuihuo0.'</td>';sanwei($val['order_amount']-$koudian-$tuihuo0)
			$strTable .= '<td style="text-align:left;font-size:12px;color:red">'.sanwei($val['total_amount']-$koudian).'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$order_status.'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$fast_flag.'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.\date('Y-m-d H:i:s',$val['add_time']).' </td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'order');
    	exit();
    }

    public function export_order2(){
         $timegap = I('timegap');
        if($timegap){
        	$gap = explode(' - ', $timegap);
        	$begin = strtotime($gap[0]);
        	$end = strtotime($gap[1]);
        }
        // 搜索条件 STORE_ID
        $condition = array('a.store_id'=>STORE_ID); // 商家id
		I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") OR (a.mobile like "%'.I('consignee').'%")';
		I('goods_name') ? $condition['goods_name'] = array('like','%'.trim(I('goods_name')).'%'): false;
        if($begin && $end){
        	$condition['add_time'] = array('between',"$begin,$end");
        }
        I('goods_name') ? $condition['goods_name'] = array('like','%'.trim(I('goods_name')).'%'): false;
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        //I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
		if(I('order_status') == '3'){
			$condition['order_status'] = array('in','3,5');
		}elseif(I('order_status') != ''){
			$condition['order_status'] = I('order_status');
		}
		if(I('order_status') == 99){
		    $condition['order_status'] = array('not in','3,5');
		}
        //$condition['order_prom_type'] = 0;
        I('fast_flag') != '' ? $condition['c.fast_flag'] = I('fast_flag') : false;
        I('biaoshi_xian') != '' ? $condition['biaoshi_xian'] = ['like',"%".I('biaoshi_xian')."%"] : false;    
                
                
        // dump(I('order_status'));
        // dump($condition);
        // die;
        //获取订单列表
        $orderList = M('order_goods g')
		->field('g.*,c.company,c.company_address,c.mobile,c.fast_flag,a.order_sn,a.order_status,a.add_time')
		->join('ty_order a on a.order_id=g.order_id','LEFT')
		->join('ty_users c on a.user_id=c.user_id','LEFT')
		->group('g.rec_id')
		->where($condition)->order('a.order_id desc')->select();
		//echo \json_encode($condition);exit;
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">店铺-收货人</td>';
    	//$strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
    	//$strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品名称</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品规格</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品单价</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品数量</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">供应价</td>';
		//$strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货金额</td>';
// 		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">应收金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单状态</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">是否快线</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
    	$strTable .= '</tr>';
    	

    	foreach($orderList as $k=>$val){
	
		
		$orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
		$koudian=0;$koudians=0;$order_status="";
		
		if($val['order_status']==0){
			$order_status="<span style='color:red'>未发货</span>";
		}elseif($val['order_status']==1){
			$order_status="<span style='color:blue'>已发货</span>";
		}elseif($val['order_status']==2){
			$order_status="<span style='color:green'>完成</span>";
		}else{
			$order_status="作废/取消";
		}
		if($val['fast_flag'] == 1){
		    $fast_flag = '快';
		}else{
		    $fast_flag = '否';
		}
// 		foreach($orderGoods as $goods){
// 			$koudian+=\sanwei($goods['member_goods_price']*$goods['goods_num']*$goods['points']/100);
// 			$koudians+=\sanwei(($goods['member_goods_price']*$goods['goods_num']) - ($goods['member_goods_price']*$goods['goods_num']*$goods['points']/100));
// 		}
		
		unset($orderGoods);
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['company'].'</td>';
            //$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['address'].' </td>';
            //$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['mobile'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_name'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['spec_key_name'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['member_goods_price'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_num'].'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.geshi($val['member_goods_price']*$val['goods_num']).'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['points'].'%</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.geshi(($val['member_goods_price']*$val['goods_num'])-($val['member_goods_price']*($val['points']/100))*$val['goods_num']).'</td>';
			//$strTable .= '<td style="text-align:left;font-size:12px;">'.$tuihuo0.'</td>';sanwei($val['order_amount']-$koudian-$tuihuo0)
// 			$strTable .= '<td style="text-align:left;font-size:12px;color:red">'.sanwei($val['total_amount']-$koudian).'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$order_status.'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$fast_flag.'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.\date('Y-m-d H:i:s',$val['add_time']).' </td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'order');
    	exit();
    }


    //导出订单
    public function yongyou13s()
    {
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            // $begin = $end - 86400*3+60;
        }
        // dump($end);
        // dump($begin);
        // die;
        if(empty(!I('goods_name'))){
            $this->error('不支持产品条件提交导出!');exit;
        }
        
        if($end-$begin > 86400*3){
            $this->error('系统只支持2天的数据导出！');exit;
        }
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");
        import("Org.Util.PHPExcel.Writer.Excel2007");
        // 搜索条件 STORE_ID
        $condition = array('a.store_id'=>STORE_ID); // 商家id
        I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") OR (a.mobile like "%'.I('consignee').'%")';
        
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        I('order_sn') ? $condition['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;

        if(I('dayin_store')=="0"){
            $condition['dayin_store']=0;
        }elseif(I('dayin_store')== '1'){
            $condition['dayin_store']=array('gt',0);
        }

        // $order_status = intval(I('order_status'));
        // if($order_status == '3'){
        //     $condition['order_status'] = array('in','3,5');
        // }elseif($order_status === 0){
        //     unset($condition['order_status']);
        // }elseif($order_status != ''){
        //     $condition['order_status'] = $order_status;
        // }
        $condition['order_status'] = array('in','0,1,2,4');
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objActSheet = $objPHPExcel->getActiveSheet();

        $objActSheet->setCellValue('A1', '销售单号');
        $objActSheet->setCellValue('B1', '客户名称');
        $objActSheet->setCellValue('C1', '客户电话');
        $objActSheet->setCellValue('D1', '客户地址');
        $objActSheet->setCellValue('E1', '客户编码');
        $objActSheet->setCellValue('F1', '产品名称');
        $objActSheet->setCellValue('G1', '产品编号');
        $objActSheet->setCellValue('H1', '数量');
        $objActSheet->setCellValue('I1', '单位');
        $objActSheet->setCellValue('J1', '单价');
        $objActSheet->setCellValue('K1', '总金额');
        $objActSheet->setCellValue('L1', '订单日期');
        $objActSheet->setCellValue('M1', '仓库');
        $objActSheet->setCellValue('N1', '备注');
        $i=2;
        // dump($condition);
        // die;
        $orderList=M('order a')
            ->field('a.*,b.company')
            ->join('ty_users b on a.user_id=b.user_id')
            ->where($condition)->order('a.add_time asc')->select();

        // dump(count($orderList));
        // die;
        foreach($orderList as $val){
            $orderGoods = M('order_goods a')
                ->field('a.spec_key_name,a.goods_name,a.sku,a.goods_num,a.member_goods_price,a.points,b.sku,b.spu') //获取最新sku
                ->join('ty_spec_goods_price b on a.spec_key=b.key','LEFT')
                ->where('a.order_id='.$val['order_id'])->group('a.rec_id')->select();
          
            foreach($orderGoods as $k=>$v){
                // $goods_kou_total = sanwei($v['goods_num'] * sanweis(($v['member_goods_price'] - ($v['member_goods_price'] * $v['points'] /100))));
                $goods_kou_total = sanweis($v['goods_num'] * sanwei($v['member_goods_price']));
                
                $objActSheet->setCellValue('A'.$i, 'hh'.$val['order_sn']);
                $objActSheet->setCellValue('B'.$i, $val['company']);
                $objActSheet->setCellValue('C'.$i, $val['mobile']); //$val['mobile']
                $objActSheet->setCellValue('D'.$i, $val['address']);
                $objActSheet->setCellValue('E'.$i, 'hh'.$val['user_id']);
                $objActSheet->setCellValue('F'.$i, $v['goods_name'].'('.$v['spec_key_name'].')');
                $objActSheet->setCellValue('G'.$i, $v['sku']);
                $objActSheet->setCellValue('H'.$i, $v['goods_num']);
                $objActSheet->setCellValue('I'.$i, $v['spu']);
                $objActSheet->setCellValue('J'.$i, sanwei($v['member_goods_price']));
                $objActSheet->setCellValue('K'.$i, $goods_kou_total);
                $objActSheet->setCellValue('L'.$i, \date('Y-m-d H:i:s',$val['add_time']));
                $objActSheet->setCellValue('M'.$i, '仓库');
                $objActSheet->setCellValue('N'.$i, '联鑫壹天达五金商城订单');

                $i++;
            }
        }
        $fileName = 'hh单据';
        $date = date("Y-m-d",time());
        $fileName .= "_{$date}.xls";
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        $objPHPExcel->getActiveSheet()->setTitle('viateams');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
	
	//导出用友t+ 13.0
	    public function yongyou13()
	    {
			$ids=I('ids');
			if(empty($ids)){
				echo '非法提交！';exit;
			}
			$e_biaoshi='hh';$e_name='联鑫壹天达五金商城';
			import("Org.Util.PHPExcel");
			import("Org.Util.PHPExcel.Worksheet.Drawing");
			import("Org.Util.PHPExcel.Writer.Excel2007");
			$objPHPExcel = new \PHPExcel(); 
			$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
			 $objActSheet = $objPHPExcel->getActiveSheet();
			        
			        $objActSheet->setCellValue('A1', '销售单号');
			        $objActSheet->setCellValue('B1', '客户名称');
			        $objActSheet->setCellValue('C1', '客户电话');
			        $objActSheet->setCellValue('D1', '客户地址');
			        $objActSheet->setCellValue('E1', '客户编码');
					$objActSheet->setCellValue('F1', '产品名称');
					$objActSheet->setCellValue('G1', '产品编号');
					$objActSheet->setCellValue('H1', '数量');
					$objActSheet->setCellValue('I1', '单位');
					$objActSheet->setCellValue('J1', '单价');
					$objActSheet->setCellValue('K1', '总金额');
					$objActSheet->setCellValue('L1', '订单日期');
					$objActSheet->setCellValue('M1', '仓库');
					$objActSheet->setCellValue('N1', '备注');
					
					$i=2;
					$orderList=M('order a')
					->field('a.*,b.company')
					->join('ty_users b on a.user_id=b.user_id')
					->where('a.order_id in('.$ids.')')->select();

					foreach($orderList as $val){
					$orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
					
					foreach($orderGoods as $k=>$v){
						$objActSheet->setCellValue('A'.$i, $e_biaoshi.$val['order_sn']);
						$objActSheet->setCellValue('B'.$i, $val['company'].$val['consignee']);
						$objActSheet->setCellValue('C'.$i, ''); //$val['mobile']
						$objActSheet->setCellValue('D'.$i, $val['address']);
						$objActSheet->setCellValue('E'.$i, $e_biaoshi.$val['user_id']);
						$objActSheet->setCellValue('F'.$i, $v['goods_name'].'('.$v['spec_key_name'].')');
						$objActSheet->setCellValue('G'.$i, $v['sku']);
						$objActSheet->setCellValue('H'.$i, $v['goods_num']);
						$objActSheet->setCellValue('I'.$i, '件');
						$objActSheet->setCellValue('J'.$i, $v['member_goods_price']);
						$objActSheet->setCellValue('K'.$i, $val['order_amount']);
						$objActSheet->setCellValue('L'.$i, \date('Y-m-d H:i:s',$val['add_time']));
						$objActSheet->setCellValue('M'.$i, '仓库');
						$objActSheet->setCellValue('N'.$i, $e_name.'订单');
						
						$i++;
					}
					}
					
					  $fileName = $e_name.'订单';
					        $date = date("Y-m-d",time());
					        $fileName .= "_{$date}.xls";
					        $fileName = iconv("utf-8", "gb2312", $fileName);
					        //重命名表
					        $objPHPExcel->getActiveSheet()->setTitle('viateams');
					        //设置活动单指数到第一个表,所以Excel打开这是第一个表
					        $objPHPExcel->setActiveSheetIndex(0);
					        header('Content-Type: application/vnd.ms-excel');
					        header("Content-Disposition: attachment;filename=\"$fileName\"");
					        header('Cache-Control: max-age=0');
					        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
					        $objWriter->save('php://output'); //文件通过浏览器下载
			exit;
	    }
	
//导出秒帐
    public function miaozhang()
    {
		$ids=I('ids');
		if(empty($ids)){
			echo '非法提交！';exit;
		}
		import("Org.Util.PHPExcel");
		import("Org.Util.PHPExcel.Worksheet.Drawing");
		import("Org.Util.PHPExcel.Writer.Excel2007");
		$objPHPExcel = new \PHPExcel();
		$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
		 $objActSheet = $objPHPExcel->getActiveSheet();
		        
		        $objActSheet->setCellValue('A3', '销售单号');
		        $objActSheet->setCellValue('B3', '客户名称');
		        $objActSheet->setCellValue('C3', '销售日期');
		        $objActSheet->setCellValue('D3', '送货日期');
		        $objActSheet->setCellValue('E3', '整单折扣(%)');
		        $objActSheet->setCellValue('F3', '计划收款日期');
				$objActSheet->setCellValue('G3', '产品名称');
				$objActSheet->setCellValue('H3', '赠品');
				$objActSheet->setCellValue('I3', '客户货号');
				$objActSheet->setCellValue('J3', '总数量');
				$objActSheet->setCellValue('K3', '单位');
				$objActSheet->setCellValue('L3', '单价');
				$objActSheet->setCellValue('M3', '进价');
				$objActSheet->setCellValue('N3', '已送数量');
				$objActSheet->setCellValue('O3', '已收款');
				$objActSheet->setCellValue('P3', '收款账户');
				$objActSheet->setCellValue('Q3', '收款日期');
				$objActSheet->setCellValue('R3', '仓库');
				$objActSheet->setCellValue('S3', '备注');
				
				$i=4;
				$orderList=M('order')->where('order_id in('.$ids.')')->select();
				foreach($orderList as $val){
				$orderGoods = D('order_goods')->where('order_id='.$val['order_id'])->select();
				
				foreach($orderGoods as $k=>$v){
					$objActSheet->setCellValue('A'.$i, '众创织梦'.$val['order_sn']);
					$objActSheet->setCellValue('B'.$i, '众创织梦商城');
					$objActSheet->setCellValue('C'.$i, \date('Y/m/d',$val['add_time']));
					$objActSheet->setCellValue('D'.$i, \date('Y/m/d',$val['add_time']));
					$objActSheet->setCellValue('E'.$i, '');
					$objActSheet->setCellValue('F'.$i, \date('Y/m/d',$val['add_time']));
					$objActSheet->setCellValue('G'.$i, $v['goods_name'].'('.$v['spec_key_name'].')');
					$objActSheet->setCellValue('H'.$i, '');
					$objActSheet->setCellValue('I'.$i, $v['sku']);
					$objActSheet->setCellValue('J'.$i, $v['goods_num']);
					$objActSheet->setCellValue('K'.$i, '件');
					$objActSheet->setCellValue('L'.$i, $v['member_goods_price']);
					$objActSheet->setCellValue('M'.$i, 0);
					$objActSheet->setCellValue('N'.$i, '');
					$objActSheet->setCellValue('O'.$i, '');
					$objActSheet->setCellValue('P'.$i, '');
					$objActSheet->setCellValue('Q'.$i, \date('Y/m/d',$val['add_time']));
					$objActSheet->setCellValue('R'.$i, '仓库');
					$objActSheet->setCellValue('S'.$i, '众创织梦商城订单');
					
					$i++;
				}
				}
				
				  $fileName = '众创织梦秒帐单据';
				        $date = date("Y-m-d",time());
				        $fileName .= "_{$date}.xls";
				        $fileName = iconv("utf-8", "gb2312", $fileName);
				        //重命名表
				        $objPHPExcel->getActiveSheet()->setTitle('销售单V2.5');
				        //设置活动单指数到第一个表,所以Excel打开这是第一个表
				        $objPHPExcel->setActiveSheetIndex(0);
				        header('Content-Type: application/vnd.ms-excel');
				        header("Content-Disposition: attachment;filename=\"$fileName\"");
				        header('Cache-Control: max-age=0');
				        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
				        $objWriter->save('php://output'); //文件通过浏览器下载
		exit;
    }
	
    /**
     * 初始化编辑器链接     
     * 本编辑器参考 地址 http://fex.baidu.com/ueditor/
     */
    private function initEditor()
    {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp',array('savepath'=>'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp',array('savepath'=>'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp',array('savepath'=>'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp',array('savepath'=>'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage',array('savepath'=>'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager',array('savepath'=>'article'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie',array('savepath'=>'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }    
	
    /**
     * 添加一笔订单
     */
    public function add_order()
    { 
        $jssdk = new \Mobile\Logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
        $order = array('store_id'=>STORE_ID);
		$action=I('action');
        //  获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //  获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        //  获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        if(IS_POST)
        {

			$users_fenbu_id=M('users')->where('user_id='.I('user_id'))->getField('fenbu_id');

            //首单金额：查询用户是否第一次下单
            $is_order = M('Order')->where('user_id = '.I('user_id'))->find();


			$dai_type=1;
			$user_name=I('consignee') ? I('consignee') : I('user_name');
            $order['user_id'] = I('user_id');// 用户id 可以为空
            $order['consignee'] = $user_name;// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址 {"4722":{"18316":{"goods_num":"1"}}}
            $order['mobile'] = I('mobile'); // 手机
            $order['invoice_title'] = I('invoice_title');// 发票
			$order['fenbu_id'] = \session('fenbu_ids')?\session('fenbu_ids'):0;
			$order['ufenbu_id'] =$users_fenbu_id?$users_fenbu_id:0;

            //$order['admin_note'] = I('admin_note'); // 管理员备注
			if($dai_type == 2){ //如果是特殊代客下单
			if(I("goods_id"))
				$goods_id_arr = I("goods_id");
			else
				$goods_id_arr =\json_decode('{"4722":{"18316":{"goods_num":"1"}}}',true);

				$order['order_sn'] = I('order_sn'); // 订单编号;
				$order['jian_count'] = I('biaoqian'); // 标签数;
			}else{
				$goods_id_arr = I("goods_id");
				$order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
				$order['master_order_sn'] = $this->get_order_sn(); // 合并订单编号;
			}

            $order['user_note'] = I('user_note'); // 单据备注
			$order['fujian'] = I('fujian'); // 附件
            $order['add_time'] = time();
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');
            $order['pay_code'] = I('payment')?I('payment'):'cod';// 支付方式
			$order['dai_type'] = $dai_type;
            // $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');
            $order['pay_name'] = '货到付款';

            $orderLogic = new OrderLogic();
            $order_goods = $orderLogic->get_spec_goods($goods_id_arr);

            foreach ($order_goods as $k=>$v){
                $float = check_float(STORE_ID,I('user_id'),$v['goods_id']);
                // $order_goods[$k]['floating'] = $v['floating']+$float;
                if($float != 0){
                    $order_goods[$k]['member_goods_price'] = $v['member_goods_price'] + ($v['member_goods_price']*($float/100));
                }


            }
                        // dump($order_goods);
            // die;
			$kehu_pd=M('users')->where('company="'.trim($user_name).'" and store_id='.STORE_ID)->find();
			if(empty($kehu_pd) && I("dai_type")=='2'){
			$user_id=M('users')->add([
				'reg_time'=>\time(),
				'mobile'=>I('mobile'),
				'is_lock'=>0,
				'nick_name'=>$user_name,
				'nickname'=>$user_name,
				'biaoshi'=>'客户',
				'biaoshi_xian'=>I('biaoshi_xian'),
				'company'=>$user_name,
				'company_address'=>I('address'),
				'store_id'=>STORE_ID
			]); //添加用户
			$order['user_id']=$user_id;
			}
		if($dai_type=='2'){
			$result['result']['goods_price']=I('z_jine');
//			$result['result']['member_goods_price']=I('z_jine');
			$result['result']['store_shipping_price']=I('z_jine');
			$result['result']['order_amount']=I('z_jine');
			$result['result']['total_amount']=I('z_jine');
		}else{
			$result = calculate_price($order['user_id'],$order_goods, array(STORE_ID => $order['shipping_code']), 0,$order[province],$order[city],$order[district],0,0,0,0,'线下',11);
			if($result['status'] < 0)
            {
                 $this->error($result['msg']);
            }
		}

           foreach ($order_goods as $key=>$val){
                if($val['goods_num']>0){
                     $spec_goods_price = M('spec_goods_price')->where(['goods_id'=>$val['goods_id'],'key'=>$val['spec_key']])->getField('store_count');
                     if($spec_goods_price < $val['goods_num']){
                        $this->error($val['goods_name'].'库存不足');
                        die;
                     }
                 }
            }

            $smoe_sn = date('YmdHis').substr(microtime(), 2, 5).mt_rand(10000,99999);

           $order['same_order']    = $smoe_sn; // 商品总价
           $order['goods_price']    = $result['result']['goods_price']; // 商品总价
           $order['shipping_price'] = $result['result']['store_shipping_price'][STORE_ID]; //物流费
           $order['order_amount']   = $result['result']['order_amount']; // 应付金额
           $order['total_amount']   = $result['result']['total_amount']; // 订单总价
           $order['yijia_heji']     = $result['result']['yijia_heji_s']; //溢价收益
           $order['kou_price']     = $result['result']['kou_price_s']; //溢价收益
            // dump($order);
            // die;

            $level_quota = M('user_level')->where(['level_id'=>$order['user_id']])->getField('quota');

            if($level_quota > 0 && $result['result']['order_amount'] < $level_quota){
                $diff_price = $level_quota - $result['result']['order_amount'];
                $this->error('提交订单失败，差'.$diff_price.'金额满足下单条件');
                die;
            }

            $order_id = M('order')->add($order);
            // 添加订单
            $user_data = [
                    'user_id'          =>I('user_id'), // 用户id
                    'order_id'          =>$order_id, // 用户id
                    'price'             =>$order['order_amount']+$order['yijia_heji'],
                    'store_id'         =>STORE_ID,  // 店铺id
                    'add_time'         =>time(), // 下单时间
                    'status'         =>0, // 下单时间
                ];
            M('users_price')->add($user_data);

            //首单金额：写入数据
            if (!$is_order){
                M('users')->where('user_id = '.I('user_id'))->save([
                    first_order_amount => $order['total_amount'],
                    first_order_time => time(),
                    first_order_ids => $order_id
                ]);
            }

            $time = time();
            if($order_id)
            {
                $koudian = 0;
                $goods_gzh_name  ='';
                foreach($order_goods as $key => $val)
                {
                    $goods = M('goods')->where("goods_id =".$val['goods_id'])->find();
                    $goods_gzh_name .=$val['goods_name'].",";
                    if(!empty($goods['fenbu_koudian'])){
                        $goods['fenbu_koudian'] = json_decode($goods['fenbu_koudian'],true);
                        foreach ($goods['fenbu_koudian'] as $kk=>$vv){
                            if($vv['fenbu_id'] == $users_fenbu_id){
                                if(!empty($vv['fenbu_koudian']) && $vv['fenbu_koudian']!=0){
                                    $goods['points'] = $vv['fenbu_koudian'];
                                    break;
                                }
                            }
                        }
                    }

                    //判断是否存在活动，存在活动是否有设置扣点
                    if($val['zd'] != 1){
                        if($val['prom_id'] > 0){
                            $prom = M('prom_goods')->where('id = '.$val['prom_id'].' and start_time <='.$time.' and end_time>='.$time.' and goods_key like "%'.$val['spec_key'].'%"')->getField('prom_kou');
                            if(!empty($prom)){
                                if($prom > 0){
                                    $goods['points'] = $prom;
                                }
                            }
                        }
                    }




                    $nyj=yj_price($val['goods_id'],$val['member_goods_price'],$users_fenbu_id);
                    $val['order_id'] = $order_id;
                    $val['store_id'] = STORE_ID;
                    $val['yijia'] = $nyj;
                    $val['points'] = $goods['points'];
                    $val['full_status'] = $goods['prom_lock'];
                    $rec_id = M('order_goods')->add($val);
                    $koudian += ($val['member_goods_price'] * ($val['points']/100))*$val['goods_num'];
                    M("order_yijia")->data([
                        'order_sn'=>$order['order_sn'],
                        'order_id'=>$order_id,
                        'goods_id'=>$val['goods_id'],
                        'store_id'=>STORE_ID,
                        'consignee'=>$order['consignee'],
                        'spec_key'=>$val['spec_key'],
                        'goods_num'=>$val['goods_num'],
                        'y_price'=>$val['member_goods_price'],
                        'price'=>$nyj,
                        'fenbu_id'=>$users_fenbu_id,
                        'add_time'=>\time()
                    ])->add(); //写入溢价分成表
                     if(!empty($val['spec_key'])){
                         M('spec_goods_price')->where("goods_id = ".$val['goods_id']." and `key`='".$val['spec_key']."'")->setDec('store_count',(int)$val['goods_num']);

                    }

                     if($val['is_yanzhi'] == 1){
                          M('order_yanzhi')->add([
                          'goods_id'=>$val['goods_id'],
                          'order_id'=>$order_id,
                          'key'=>$val['spec_key'],
                          'price'=>$val['member_goods_price'],
                          'points'=>$val['points'],
                          'yijia'=>$val['yijia'],
                          'goods_num'=>$val['goods_num'],
                          'add_time'=>time()]
                          );
                        }
                    $mygoods.=$val['goods_id'].'|'.$val['goods_num'].'|'.$val['spec_key'].','; //记录产品。
                    if(!$rec_id)
                        $this->error('添加失败');
                }
                logOrder($order_id,'您提交了订单，请等待系统确认','提交订单',$order['user_id'],2,$mygoods);   
                M('order')->where(['order_id'=>$order_id])->save(['kou_price'=>$koudian]);
                $store = M('store')->where(['store_id'=>STORE_ID])->find();
				  if($store['store_openid']){
                    if($store['bing_wx'] == 1){
                        $url = "pages/order_details/order_details?id=".$order_id.'&user_id='.$users_dizi['user_id'];
                        $wx_content = [];
                        $wx_content['touser'] = $store['store_openid'];
                        $wx_content['template_id'] = 'abjjdm52Y03djbYdS2aV8mqvxxXqGBynjgSpUysxlKI';
                        $wx_content['data'] = [
                            'character_string1'=>['value'=>$order['order_sn']],
                            'amount2'=>['value'=>$order['total_amount'].'元'],
                            'thing3'=>['value'=>$user_name],
                            'time4'=>['value'=>date('Y-m-d H:i:s')],
                            'thing7'=>['value'=>mb_substr($goods_gzh_name,0,16).'..'],
                            ];
                        $wx_content['miniprogram'] = ['appid'=>'wx5427cce6d89fe90a','pagepath'=>$url];
                        $json = json_encode($wx_content);
                		$a = $jssdk->push_msg_mod($json);
                		dump($a);
                    }
                }
				if($dai_type=='2'){
					M('order_jian')->where('order_id='.$order_id)->delete();//删除出入库重写写入记录/index.php?m=Seller&c=Order&a=add_order&action=1
					for($i=1;$i<=(int)I('biaoqian');$i++){
						M('order_jian')->add([
							"order_id"=>$order_id,
							"ruku_num"=>$i,
							"chuku_num"=>$i
						]);
					}
					$this->success('添加订单成功',"/index.php/Seller/Order/biaoqian_print/order_id/".$order_id);
				}else{
					$this->success('添加订单成功',U("Order/detail",array('order_id'=>$order_id)));
				}

                exit();
            }
            else{
                $this->error('添加失败');
            }
        }
		$this->initEditor(); // 编辑器
		$this->assign('myurl',SITE_URL);
		$this->assign('action',$action);
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->assign('province',$province);
        $this->assign('store_id',STORE_ID);
        $this->display();
    }

    /**
     * 订单编辑
     * @param int $id 订单id
     */
    public function edit_order(){
    	$order_id = I('order_id');
		if(empty($order_id))
		$this->error('非法操作！');
		
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
		if(empty($order))
			$this->error('非法操作！');

 		if($order && $order['coupon_price'] > 0){
             $coupon = M('coupon')->where('coupon_id='.$order['coupon_id'])->find();
             if($coupon['store_id'] == 0){
                 $this->error('订单存在平台优惠券，禁止修改！');
             }
         }
		if(\session('fenbu_id')!=0){
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }
		}
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        // dump($orderGoods);
       	if(IS_POST)
        {
            // dump(I(""));
            // die;
            $order['consignee'] = I('consignee');// 收货人
            $order['province'] = I('province'); // 省份
            $order['city'] = I('city'); // 城市
            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机           
            $order['invoice_title'] = I('invoice_title');// 发票
            //$order['admin_note'] = I('admin_note'); // 管理员备注
			$order['user_note'] = I('user_note'); // 管理员备注
			$order['fujian'] = I('fujian'); // 附件
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');
			
            $goods_id_arr = I("goods_id");
            $new_goods = $old_goods_arr = array();
            //################################订单添加商品
            if($goods_id_arr){
            	$new_goods = $orderLogic->get_spec_goods($goods_id_arr);
            	foreach($new_goods as $key => $val)
            	{
            		$val['order_id'] = $order_id;
                    $val['store_id'] = STORE_ID;
            		$rec_id = M('order_goods')->add($val);//订单添加商品
            		if(!$rec_id)
            			$this->error('添加失败');
            	}
				
            }
           
            //################################订单修改删除商品 
            $old_goods = I('old_goods');
            $old_price = I('old_price');
			// foreach ($orderGoods as $val){ //检查库存是否充足
			// 	$pd_count=M('spec_goods_price')->where('goods_id='.$val['goods_id'].' and `key`="'.$val['spec_key'].'"')->getField('store_count');
			// 	if($pd_count<$val['goods_num']){
			// 		//$this->error($val['goods_name'].' 库存不足，无法修改！');
			// 	}
			// }

            foreach ($orderGoods as $val){
                
            	if(empty($old_goods[$val['rec_id']])){
            		M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
            	}else{
            		//修改商品数量
            		if($old_goods[$val['rec_id']] != $val['goods_num']){
            			$val['goods_num'] = $old_goods[$val['rec_id']];
            			M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
            		}

                    if($old_price[$val['rec_id']] != $val['goods_price']){
                        $val['goods_price'] = $old_price[$val['rec_id']];
                        $val['member_goods_price'] = $old_price[$val['rec_id']];
                        $nyj=yj_price($val['goods_id'],$val['member_goods_price'],$order['ufenbu_id']);
                        M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_price'=>$val['goods_price'],'member_goods_price'=>$val['member_goods_price'],'yijia'=>$nyj));
                    }
            		$old_goods_arr[] = $val;
            	}
            }
			
            $s_stored_id = M('coupon_list')->where("uid = ".$order['user_id']." and order_id = $order_id")->find();
            if($s_stored_id)
                $coupon_array[$s_stored_id['store_id']] = $s_stored_id['id'];
            else{
            	$coupon_array = array();
            } 
            $coupon_id = $coupon_array;
            $goodsArr = array_merge($old_goods_arr,$new_goods);
    
			if(I("dai_type")=='2'){
				$result['result']['goods_price']=I('z_jine');
				$result['result']['store_shipping_price']=I('z_jine');
				$result['result']['order_amount']=I('z_jine');
				$result['result']['total_amount']=I('z_jine');
					$u=M('users')->where('user_id='.$order['user_id'].' and store_id='.STORE_ID)->save([
					'mobile'=>I('mobile'),
					'nick_name'=>I('consignee'),
					'nickname'=>I('consignee'),
					'company'=>I('company'),
					'company_address'=>I('address')
				]);
			}else{
				 $result = calculate_price($order['user_id'],$goodsArr,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],$order['integral'],0,$coupon_id,0,'线下',11);
				if($result['status'] < 0)	
			    {
			         $this->error($result['msg']);
			    } 
			}
			$coupon_price = 0;
			if($order['coupon_price'] > 0){
			    
			    if($result['result']['order_amount'] > $order['order_amount']){
			        $coupon_price = $order['coupon_price'];
			    }else{
			        $Proportion = $order['coupon_price']/$order['order_amount'];//原价格比例
			        $coupon_price = geshi($result['result']['order_amount']*$Proportion);//修改玩新价格之后的优惠价
			    }
			    
			}
 //echo json_encode($result);exit;
            //################################修改订单费用
            $order['goods_price']    = $result['result']['goods_price']; // 商品总价
            $order['shipping_price'] = $result['result']['shipping_price'];//物流费
            $order['order_amount']   = $result['result']['order_amount']-$coupon_price; // 应付金额
            $order['total_amount']   = $result['result']['total_amount']; // 订单总价
			$order['yijia_heji']   = $result['result']['yijia_heji_s']; // 订单yijia
			$order['kou_price']   = $result['result']['kou_price_s']; // 订单收益
			$order['coupon_price']   = $coupon_price; // 订单收益
            $super = session('shadow');
            if($super == 'shadow'){
                $order['update_status'] = 1;
            }else{
                $order['update_status'] = 2;
            }
            $order['update_time'] = time();
            $order['update_ip'] = get_client_ip();
            $o = M('order')->where("order_id = $order_id and store_id =".STORE_ID)->save($order);
            M('users_price')->where('order_id='.$order_id)->setField(['price'=>$order['yijia_heji']+$order['order_amount']]);
            //如果有一个规格多个数据合并
            $order_goodsArr = M('order_goods')->where(['order_id'=>$order_id])->select();
            foreach($order_goodsArr as $k=>$v){
                 $order_goodsCount = M('order_goods')->where(['spec_key'=>$v['spec_key'],'order_id'=>$order_id])->count();
                 if($order_goodsCount >= 2){//有重复的进来合并
                     $order_goodsData = M('order_goods')->where(['spec_key'=>$v['spec_key'],'order_id'=>$order_id])->find();//原始数据
                     $order_goodsSum = M('order_goods')->where(['spec_key'=>$v['spec_key'],'order_id'=>$order_id,'rec_id'=>['neq',$order_goodsData['rec_id']]])->sum('goods_num');//计算出其余数量 
                     M('order_goods')->where(['spec_key'=>$v['spec_key'],'order_id'=>$order_id,'rec_id'=>['neq',$order_goodsData['rec_id']]])->delete();//删除原始数据以外的所有数据
                     M('order_goods')->where(['rec_id'=>$order_goodsData['rec_id']])->save(['goods_num'=>$order_goodsData['goods_num']+$order_goodsSum]);

                 }
            }
            
            
			$seller_id = session('seller_id');
            $l = $orderLogic->orderActionLog($order,'edit','修改订单',$seller_id,1);//操作日志
            	$this->success('修改成功',U('Order/edit_order',array('order_id'=>$order_id)));

            exit;
        }
        // 获取省份
        $province = M('region')->where(array('parent_id'=>0,'level'=>1))->select();
        //获取订单城市
        $city =  M('region')->where(array('parent_id'=>$order['province'],'level'=>2))->select();
        //获取订单地区
        $area =  M('region')->where(array('parent_id'=>$order['city'],'level'=>3))->select();
        //获取支付方式
        $payment_list = M('plugin')->where(array('status'=>1,'type'=>'payment'))->select();
        //获取配送方式
        $shipping_list = M('plugin')->where(array('status'=>1,'type'=>'shipping'))->select();
        
		$this->initEditor(); // 编辑器
        $this->assign('order',$order);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('area',$area);
        $this->assign('orderGoods',$orderGoods);
        $this->assign('shipping_list',$shipping_list);
        $this->assign('payment_list',$payment_list);
        $this->display();
    }
    

    /**
     * 选择搜索商品添加附件
     */
    public function search_goodss()
    {
    	$categoryList =  M("store_goods_class")->where('store_id='.STORE_ID.' and parent_id = 0')->select();
    	$this->assign('categoryList',$categoryList);	
    	$where = ' store_id = '.STORE_ID.' and  is_on_sale = 1 ';//搜索条件
    	//I('intro')  && $where = "$where and ".I('intro')." = 1";
        
        $cat_id = I('cat_id'); //echo $cat_id;exit;
    	if($cat_id){
            $goods_category = M('store_goods_class')->where("cat_id = $cat_id")->find();
            $where = " $where  and store_cat_id1 = $cat_id "; // 初始化搜索条件
            $this->assign('cat_id',$cat_id);
    	}
    	if(!empty($_REQUEST['keywords']))
    	{
    		$this->assign('keywords',I('keywords'));
    		$where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%') and is_on_sale=1 and store_id = ".STORE_ID;
    	}  	
    	$goodsList = M('goods')->where($where)->order('goods_id DESC')->limit(100)->select();
                
        // foreach($goodsList as $key => $val)
        // {
        //     $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
        //     $goodsList[$key]['spec_goods'] = $spec_goods;            
        // }
        
        
        $this->assign('cat_id',$cat_id);
    	$this->assign('goodsList',$goodsList);
    	$this->display();
    }
	
    /**
     * 订单选择搜索商品
     */
    public function search_goods()
    {
        $order_id = I('order_id');
        $spec_key='';
        if($order_id){
            $spec_key = M('order_goods')->where(['order_id'=>$order_id])->select();
        }
    	$where = ' is_on_sale = 1 and is_delete=0 and goods_state=1 and store_id ='.STORE_ID.' ';//搜索条件
    	if(!empty($_REQUEST['keywords']))
    	{
    		$this->assign('keywords',I('keywords'));
    		$where = "$where and (goods_name like '%".I('keywords')."%' or keywords like '%".I('keywords')."%')" ;
    	}  	
    	$goodsList = M('goods')->where($where)->order('goods_id DESC')->limit(100)->select();
                
        foreach($goodsList as $key => $val)
        {
            $spec_goods = M('spec_goods_price')->where("goods_id = {$val['goods_id']}")->select();
			foreach($spec_goods as $keys=>$vs){
                $spec_goods[$keys]['is_yes']=0;
			    if($spec_key){
			        foreach ($spec_key as $item){
			            if($item['spec_key'] == $vs['key']){
                            $spec_goods[$keys]['is_yes']=1;
                        }
                    }
                }
				$new_price=get_goods_huodong($val['goods_id'],$vs['key']);
				$spec_goods[$keys]['price']=$new_price;
			} 
    //        if($val['prom_id']!=0){
			 //   foreach($spec_goods as $keys=>$vs){
				// 	$spec_goods[$keys]['price']=$vs['price']*($val['floating']/100)*$zhekou/100;
				// } 
		  //  }else{
			 //   foreach($spec_goods as $keys=>$vs){
			 //   		$spec_goods[$keys]['price']=$vs['price']*$val['floating']/100;
			 //   	} 
		  //  }
			
			$goodsList[$key]['spec_goods'] = $spec_goods;
        }


    	$this->assign('goodsList',$goodsList);
    	$this->display();        
    }
	
    public function ajaxOrderNotice(){
        $order_amount = M('order')->where(array('order_status'=>0))->count();
        echo $order_amount;
    }
	
    /*
     *订单退货首页 
     */
    public function tuihuo_list(){
        $orderLogic = new OrderLogic();
		$timegap = I('timegap');
		if($timegap){
			$gap = explode(' - ', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
		}
		
		
		
        // 搜索条件
        $condition = array();
        if($begin && $end){
        	$condition['tuihuo_time'] = array('between',"$begin,$end");
        }
//         if(session('fenbu_ids') == "0" || session('fenbu_ids') == "42"){
// 		    $condition['print_num'] = ['gt',0];
// 		}
        I('status')!="" ? $condition['status'] = I('status') : false;
        I('getorder')!="" ? $condition['getorder'] = I('getorder') : false;
        I('return_order_sn')!="" ? $condition['return_order_sn'] = ['like','%'.I('return_order_sn').'%'] : false;
		//I('order_sn') ? $condition['remark'] = array('like','%'.trim(I('order_sn')).'%') : false;
		I('order_sn') && $condition['_string'] = ' (a.order_sn like "%'.I('order_sn').'%")  OR (a.remark like "%'.I('order_sn').'%") ';
		I('consignee') && $condition['_string'] = ' (b.nickname like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") ';
		$condition['a.store_id']=STORE_ID;
		$condition['a.status']=['neq',3];
// 		dump($condition);
        $count = M('return_goods a')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->where($condition)->count();
        $Page  = new Page($count,20);
        //  搜索条件下 分页赋值

        $show = $Page->show();
        //获取订单列表
		$orderList = M('return_goods a')
		->field('a.*,b.*,c.original_img as imgs,c.goods_name,d.key_name,e.fenbu_name,a.ruku_time as ruku_time')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->join('ty_spec_goods_price d ON a.spec_key=d.key','LEFT')
		->join('ty_fenbu e ON b.fenbu_id=e.fenbu_id','LEFT')
		->where($condition)->limit("$Page->firstRow,$Page->listRows")
		->order('a.id desc')
		->group('a.id')
		->select();
		foreach ($orderList as $k=>$v){
		    if(!empty($v['ruku_time'])){
		        $orderList[$k]['ruku_time'] = date('Y-m-d H:i:s');
		    }else{
		        $orderList[$k]['ruku_time'] = '';
		    }
		}
        // dump($orderList);
		//echo json_encode($orderList);exit;
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
	
	public function export_order_tuihuo(){
	    $orderLogic = new OrderLogic();
		$timegap = I('timegap');
		if($timegap){
			$gap = explode(' - ', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
		}
		
	    // 搜索条件
	    $condition = array();
	    if($begin && $end){
	    	$condition['tuihuo_time'] = array('between',"$begin,$end");
	    }

        I('getorder')!="" ? $condition['getorder'] = I('getorder') : false;
	    I('status')!="" ? $condition['status'] = I('status') : false;
        I('return_order_sn')!="" ? $condition['return_order_sn'] = I('return_order_sn') : false;
		I('order_sn') ? $condition['remark'] = array('like','%'.trim(I('order_sn')).'%') : false;
		I('consignee') && $condition['_string'] = ' (b.nickname like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") ';
		$condition['a.store_id']=STORE_ID;
		
	    //获取订单列表
		$orderList = M('return_goods a')
		->field('a.*,b.*,c.original_img as imgs,c.goods_name,d.key_name,e.fenbu_name')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->join('ty_spec_goods_price d ON a.spec_key=d.key','LEFT')
            ->join('ty_fenbu e ON b.fenbu_id=e.fenbu_id','LEFT')

		->where($condition)->order('a.id desc')->select();

	
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">原单号</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">区域</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">买家</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">产品名称</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">单价</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单价</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">应扣金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货时间</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="100">取货状态</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="100">取货时间</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="100">扣费状态</td>';
    	$strTable .= '</tr>';
		
		foreach($orderList as $k=>$val){ 
			$dsprice=(float)$val['member_goods_price']*(float)$val['goods_num']; //订单价
			$ptprice=$dsprice*($val['points']/100); //平台价
			$ptprices=$dsprice-$ptprice;
			if($val['status']==2)
				$zhuangtai='<span style="color: green">已扣费</span>';
            elseif($val['status']==3)
                $zhuangtai='<span style="color: blue">已取消</span>';
            else
				$zhuangtai='<span style="color: red">未扣费</span>';

            if($val['getorder']==1){
                $getorder='<span style="color: green">已取货</span>';
            }elseif ($val['getorder']==2){
                $getorder='<span style="color: black">未入库</span>';
            }else{
                $getorder='<span style="color: red">未取货</span>';
            }


			
						$strTable .= '<tr>';
                        $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['return_order_sn'].'</td>';
                        $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
                        $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['fenbu_name'].'</td>';
						$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['company'].'</td>';
			            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_name'].'</td>';
			    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['member_goods_price'].'</td>';
						$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_num'].' </td>';
			    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$dsprice.'</td>';
						$strTable .= '<td style="text-align:left;font-size:12px;">'.$ptprice.'</td>';
						$strTable .= '<td style="text-align:left;font-size:12px;">'.$ptprices.'</td>';
						$strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$val['tuihuo_time']).'</td>';
			    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$getorder.'</td>';
			    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$zhuangtai.'</td>';
			    		$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['getorder_time'].'</td>';
                        $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['remark'].'</td>';
			    		$strTable .= '</tr>';
		}
		$strTable .='</table>';
		unset($orderList);
		downloadExcel($strTable,'order_tuihuo');
		exit();
	}

    public function tuihuo_edit_order(){
    	$id = I('id');
		$where=array();
		if($id){
			$where['id']=$id; //如果是修改。
			
			$orderGoods=M('return_goods a')
			->field('a.*,b.nickname,b.company,c.store_name,c.store_phone,d.goods_name')
			->join('ty_users b on a.user_id=b.user_id','LEFT')
			->join('ty_store c on a.store_id=c.store_id','LEFT')
			->join('ty_goods d on a.goods_id=d.goods_id','LEFT')
			->where($where)->find();
			$spec=M('spec_goods_price')->where('`key`="'.$orderGoods['spec_key'].'"')->find();
				$orderGoods['guige']=$spec['key_name'];
		}
		
        $this->assign('order',$orderGoods);
        $this->display();
    }
	/**
	 * 订单批量打印  
	 * @param int $id 订单id
	 */
	public function order_print_pl(){
		$order_ids = I('order_ids');
		if(empty($order_ids))
			$this->error('非法操作！');
			
	    // 搜索条件
		$orderLogic = new OrderLogic();
	    $orders = M('order a')
	    ->field('a.*,b.mobile,b.company,b.nickname,b.biaoshi,b.biaoshi_xian,c.biaoqian_print,c.printb_w,c.printb_h,c.printd_w,c.printd_h,c.orders_print,b.fast_flag,a.kou_price as kou_price,a.total_amount as total_amount')
	    ->join('ty_users b on a.user_id=b.user_id','LEFT')
	    ->join('ty_store c on a.store_id=c.store_id',"LEFT")
	    ->where("a.order_id in($order_ids) and a.store_id=".STORE_ID)->order('order_id desc')->select();
		
		$store=M('store')->where("store_id=".STORE_ID)->find();
	    if(!empty($store['store_phone'])){
	        if($store['phone_status'] == 0){
	            $store['store_phone'] = '********';
	        }
	    }
		$print_data=$print_datab=[];
        // 获取店铺活动
        $activity = M('goods_full')->where([
            'store_id' => STORE_ID,
            'start_time' => ['elt', time()],
            'end_time' => ['egt', time()]
        ])->order('id desc')->find();
		foreach($orders as $key=>$vs){

			//批量打印单据
			if($vs['order_id']){ 
				$orders[$key]['full_address'] = getRegionName($vs['province']).' '.getRegionName($vs['city']).' '.getRegionName($vs['district']).' '. $vs['address'];
				$orders[$key]['g_list'] = $orderLogic->getOrderGoods($vs['order_id']);
			
				
				update_user_level($vs['user_id']);
				$fast_flag = M('users')->where("user_id=".$vs['user_id'])->getField('fast_flag');
                $fast_flag2 = M('store')->where("store_id=".$vs['store_id'])->getField('fast_flag');

                if($fast_flag && $fast_flag2){
                    $fast_text = '快';
                }else{
                    $fast_text = '';
                }
                $koudian = 0;
                 foreach ($orders[$key]['g_list'] as $k=>$v){
                        $koudian += (($v['points']/100)*$v['member_goods_price'])*$v['goods_num'];
                        if($v['prom_id'] != 0){
                            $prom = M('prom_goods')->where(['id'=>$v['prom_id']])->find();
                            if(time() > $prom['start_time'] && time() < $prom['end_time']){
                                $orders[$key]['g_list'][$k]['huodong'] = '(活动商品)';
                            }
                        }
                     if($v['prom_type'] == 4 ){
                         //查看满赠活动多送
                         $goodsfull = M('prom_goods')->where(['id'=>$v['prom_id']])->find();
                         if($goodsfull['type'] == 4){
                             $goods_goods_keys = json_decode($goodsfull['goods_key'],true);
                             $full = explode('/',$goodsfull['expression']);
                             $goodsfull['goods_num'] = $full[0];
                             $goodsfull['send_num'] = $full[1];
                             if(in_array($v['spec_key'],$goods_goods_keys)){
                                 $msg = '满'.$goodsfull['goods_num'].'送'.$goodsfull['send_num'];
                                 //存在这个满赠活动多送的情况先，修改order_goods
                                 $freeQuantity = floor(floatval($v['goods_num']) / $goodsfull['goods_num'] *$goodsfull['send_num'] ); // 计算赠送商品数量，使用 floor 函数取整数部分
                                 if($freeQuantity > 0){

                                     // 获取 DRIVER_SET 数组最后一个键
                                     $lastKey = end(array_keys($orders[$key]['g_list']));
                                     // 解析最后一个键的数字部分
//                                     $lastNumber = (int) substr($lastKey, 2);
                                     // 生成新的键
                                     $newKey = $lastKey+1;
                                     // 复制最后一行数据
                                     $newData = $orders[$key]['g_list'][$k];
                                     // 将复制的数据添加到 DRIVER_SET 数组末尾
                                     $newData['goods_num'] = $freeQuantity;
                                     $newData['goods_name'] = $v['goods_name'].'('.$msg.')';
                                     $newData['goods_kou_price'] = 0;
                                     $newData['goods_kou_total'] = 0;
                                     $orders[$key]['g_list'][$newKey] = $newData;
                                 }
                             }
                         }
                     }
                    }
                    $vs['kou_price']= $koudian;
                if(empty($vs['coupon_price'])){
                    $vs['coupon_price'] = 0.000;
                }
                $orders[$key]['total_amount'] = sanwei($vs['total_amount'] );
                $orders[$key]['coupon_price'] = sanwei($vs['coupon_price']);
                $orders[$key]['fast_text'] = $fast_text;
                if($vs['phone_status'] == 0){
                    $vs['mobile'] = '********';
                    $orders[$key]['mobile'] = '********';
                  
                }
                if ($activity) {
                    $where = [];
                    if(!empty($activity['brand_id'])){
                        $brand_id = implode(',',json_decode($activity['brand_id'],true));
                        $where['gs.store_cat_id1'] = ['in',$brand_id];
                    }
                     if(!empty($activity['goods_id'])){
                        $goods_id = implode(',',json_decode($activity['goods_id'],true));
                        $where['gs.goods_id'] = ['in',$goods_id];
                    }
                    // 获取当天用户下单总金额
                   if($activity['type'] == 1){
                        // 获取当天用户下单总金额

                        $todayStart = strtotime('midnight', $vs['add_time']);
                        $todayEnd = strtotime('tomorrow', $vs['add_time']) - 1;
                    }else{
                        // 获取这个时间区间的
                        $todayStart = $activity['start_time'];
                        $todayEnd = $activity['end_time'];
                    } 
     
                    $where['o.user_id'] = $vs['user_id'];
                    $where['o.order_status'] = ['in','0,1,2'];
                    $where['o.store_id'] = STORE_ID;
                    $where['o.add_time'] = ['between', [$todayStart, $todayEnd]];
                            $totalAmount = M('order_goods g')
            	    ->join('ty_order o on o.order_id = g.order_id','left')
            	    ->join('ty_goods gs on gs.goods_id = g.goods_id','left')
            	    ->where($where)->sum('(g.member_goods_price+g.yijia)*goods_num');
                    // dump($totalAmount);
                    if(empty($totalAmount)){
                        $totalAmount = 0;
                    }
                    // 判断是否达到活动条件
                    $finalGift = null;
                    $gifts = json_decode($activity['full_gift'], true);
                    usort($gifts, function($a, $b) {
                        return $b['price'] <=> $a['price'];
                    });
                    foreach ($gifts as $gift) {
                        if ($totalAmount >= $gift['price']) {
                            $finalGift = $gift['gift'];
                            break;
                        }
                    }
                    if($finalGift){
                        $orders[$key]['user_note'] = $vs['user_note'].'(赠品：'.$finalGift.')';
                    }
                    
                }
                $print_data[]=[
					'jian_count'=>$vs['jian_count'],
					'biaoshi'=>$vs['biaoshi']?$vs['biaoshi']:'',
					'biaoshi_xian'=>$vs['biaoshi_xian'],
					'order_sn'=>$vs['order_sn'],
					'company'=>$vs['company'].'('.$vs['nickname'].')',
					'mobile'=>$vs['mobile'], //$vs['mobile'],
					'full_address'=>$orders[$key]['full_address'],
					'g_list'=>$orders[$key]['g_list'],
					'total_amount'=>$orders[$key]['total_amount'],
					'coupon_price'=>$vs['coupon_price'],
					'store_name'=>$store['store_name'],
					'store_phone'=>$store['store_phone'],
					'user_note'=>$vs['user_note'],
					'fast_text'=>$fast_text,
					'add_time'=>date("Y-m-d H:i",$vs['add_time'])
				];
			}
			
			 // 批量标签
			$pic_data=[];
			if($vs['jian_count']>=1){
			for($i=1;$i<=(int)$vs['jian_count'];$i++){
				$erwei=$this->mypng($vs['order_id'],$i,1);
				$pic_data[$i]=\pic64($erwei);
			}
			}
			$orders[$key]['pic_data']=$pic_data;
			$print_datab[]=[ 
				'erweima'=>$pic_data,
				'myfenbu_name'=>M('fenbu')->where('fenbu_id='.$vs['ufenbu_id'])->getField('fenbu_name'),
				'biaoshi'=>$vs['biaoshi']?$vs['biaoshi']:'',
				'biaoshi_xian'=>$vs['biaoshi_xian'],
				'jian_count'=>(int)$vs['jian_count'],
				'company'=>$vs['company'].'('.$vs['nickname'].')',
				'order_sn'=>$vs['order_sn'],
                'fast_text'=>$fast_text,
				'store_name'=>$store['store_name'],
				'shijian'=>date("Y/m/d")
			];
		}

	   //print_r(\json_encode($print_datab));
	    $this->assign('orders',$orders);
	    $this->assign('print_data',\json_encode($print_data));
		$this->assign('print_datab',\json_encode($print_datab));
		$this->assign('store',$store);
	    $this->display('print_pl');
	}


    /**
     * 获取同步订单
     * */
    public function syncOrderList(){
        $tag = I('tag');
        $begin = date('Y-m-d 00:00',(time()-30*60*60*24));//30天前
        $end = date('Y-m-d 23:59',strtotime('+1 days'));
        //获取绑定的五鲸账号
        $seller = M('sync_account')->where(['store_id'=>STORE_ID,'tag'=>$tag])->find();
        $this->assign('tag',$tag);
        $this->assign('timegap',$begin.' - '.$end);
        $this->assign('syncname',$seller['store_name']);
        $this->assign('url',C('SYNC_URL')[$tag]);

        $this->display();
    }
    /**
     * 获取同步的订单查看
     * */
    public function syncdetail(){
        $tag = I('tag');
        $param['order_id'] = I('order_id');
        $url = C('SYNC_URL')[$tag].'/WXAPI/sync/'.$tag.'orderDetail';
        $callback = httpRequest($url,'POST',$param);
        Log::record($callback,'DEBUG');
        $callback = json_decode($callback,true);
        $data = $callback['data'];
        $this->assign('tag',$tag);
        $this->assign('order',$data['order']);
        $this->assign('action_log',$data['action_log']);
        $this->assign('orderGoods',$data['orderGoods']);
        $this->assign('points_count',$data['points_count']);
        $this->assign('split',$data['split']);
        $this->assign('button',$data['button']);
        $this->assign('orderStatus',1);
        $this->display();
    }

    /**
     * 打印同步订单标签
     * */
    public function syncbiaoqian_print(){
        $tag = I('tag');
        $store = M('store')->where(['store_id'=>STORE_ID])->find();
        $this->assign('store',$store);
        $param['order_id'] = I('order_id');
        $url = C('SYNC_URL')[$tag].'/WXAPI/sync/'.$tag.'biaoqian_print';
        $callback = httpRequest($url,'POST',$param);
        Log::record($callback,'DEBUG');
        $callback = json_decode($callback,true);
        $order = $callback['data']['order'];
        $fenbu_name = $callback['data']['name'];
        $pic_data1 = $callback['data']['pic_data1'];
        $pic_data = $callback['data']['pic_data'];
        $this->assign('order',$order);
        $this->assign('myfenbu_name',$fenbu_name);
        $this->assign('pic_data1',$pic_data1);
        $this->assign('pic_data',$pic_data);
        $this->display();
    }
    /**
     * 修改广西订单标签数
     * */
    public function syncchangebiaoqian(){
        $store = M('store')->where(['store_id'=>STORE_ID])->find();
        $this->assign('store',$store);
        if($_POST){
            $tag = I('tag');
            $data['table'] = I('table'); // 表名
            $data['id_name'] = I('id_name'); // 表主键id名
            $data['order_id'] = I('order_id'); // 表主键id值
            $data['field']  = I('field'); // 修改哪个字段
            $data['value']  = I('value'); // 修改字段值
            $url = C('SYNC_URL')[$tag].'/WXAPI/sync/'.$tag.'changebiaoqian';
            $callback = httpRequest($url,'POST',$data);
            Log::record($callback,'DEBUG');
            exit($callback);

        }
    }


    /**
     * 合并订单
     * */
    public function wujingorder_actions(){
        //获取登录授权的五鲸店铺名称
        $syncInfo = M('sync_account')->where(['store_id'=>STORE_ID])->find();
        if(empty($syncInfo)){
            $this->error('没有授权店铺');
        }
        $data = [];
        $data['type'] = $_POST['type'];
        $data['order_ids'] = $_POST['order_ids'];
        $data['reason'] = $_POST['reason'];
        $data['store_name'] = $syncInfo['store_name'];
        $url = C('SYNC_URL')['wujing'].'/WXAPI/sync/wujingorder_actions';
        $callback = httpRequest($url,'POST',$data);
        Log::record($callback,'DEBUG');
        $callback = json_decode($callback,true);
        exit(json_encode($callback['status']));
    }

    /**
     * 拆分订单
     * */
    public function wujingsplit_order(){

        $data['order_id'] = I('order_id');
        $url = C('SYNC_URL')['wujing'].'/WXAPI/sync/wujingsplit_order';
        $callback = httpRequest($url,'POST',$data);
        Log::record($callback,'DEBUG');
        $callback = json_decode($callback,true);
        if(IS_POST){
            $url = C('SYNC_URL')['wujing'].'/WXAPI/sync/wujingsplit_order';
            $data = I('');
            $data['status'] = 1;
            $callback = httpRequest($url,'POST',$data);
            Log::record($callback,'DEBUG');
            $callback = json_decode($callback,true);

            if($callback['status'] == 0){
                $this->error($callback['msg']);
                exit();
            }else{
                $this->success('操作成功',U('Order/wujingdetail',array('order_id'=>$data['order_id'])));
                exit();
            }
        }

        $this->assign('order',$callback['data']['order']);
        $this->assign('goods_num_arr',json_encode($callback['data']['goods_num_arr']));
        $this->assign('orderGoods',$callback['data']['orderGoods']);
        $this->display();
    }


    /**
     * 打印同步订单
     * */
    public function syncorder_print(){
        $tag = I('tag');
        $store = M('store')->where(['store_id'=>STORE_ID])->find();

        $data['order_id'] = I('order_id');
        $url = C('SYNC_URL')[$tag].'/WXAPI/sync/'.$tag.'order_print';
        $data = I('');
        $callback = httpRequest($url,'POST',$data);
        Log::record($callback,'DEBUG');
        $callback = json_decode($callback,true);

        $this->assign('order',$callback['data']['order']);
        $this->assign('users',$callback['data']['users']);
        $this->assign('shop',$callback['data']['shop']);
        $this->assign('orders_print',$store['orders_print']);
        $this->assign('store',$callback['data']['store']);
        $this->assign('shop_info',$callback['data']['shop_info']);
        $this->assign('orderGoods',$callback['data']['orderGoods']);
        $this->assign('tag',$tag);
        $this->assign('url',$url);
        $this->display('syncorder_print');
    }

    /**
     * 订单批量打印
     * @param int $id 订单id
     */
    public function syncorder_print_pl(){
        $tag = I('tag');
        $data['order_ids'] = I('order_ids');
        $data['store_id'] = I('store_id');
        $url2 = C('SYNC_URL')[$tag].'/WXAPI/sync/'.$tag.'order_print';
        $url = C('SYNC_URL')[$tag].'/WXAPI/sync/'.$tag.'order_print_pl';
        $store = M('store')->where(['store_id'=>STORE_ID])->find();
        $this->assign('orders_print',$store['orders_print']);
        $this->assign('biaoqian_print',$store['biaoqian_print']);
        $callback = httpRequest($url,'POST',$data);
        Log::record($callback,'DEBUG');
        $callback = json_decode($callback,true);
        $this->assign('url',$url2);
        $this->assign('orders',$callback['data']['orders']);
        $this->assign('print_data',$callback['data']['print_data']);
        $this->assign('print_datab',$callback['data']['print_datab']);
        $this->assign('store',$callback['data']['store']);
        $this->assign('shop_info',$callback['data']['shop_info']);
        $this->display('syncorder_print_pl');
    }
    /**
     * 订单编辑
     * @param int $id 订单id
     */
    public function syncedit_order(){
        $tag = I('tag');
        $data['dai_type'] = I('dai_type');
        $data['order_id'] = I('order_id');
        $data['company'] = I('company');
        $data['consignee'] = I('consignee');
//        $data['address'] = I('address');
        $data['mobile'] = I('mobile');
        $data['spec'] = I('spec');
        $data['old_goods'] = I('old_goods');
        $data['user_note'] = I('user_note');
        $data['id'] = I('id');
        if(IS_POST){
            $data['act'] = 1;
        }else{
            $data['act'] = 0;
        }

        $url = C('SYNC_URL')[$tag].'/WXAPI/sync/'.$tag.'edit_order';
        $callback = httpRequest($url,'POST',$data);
        Log::record($callback,'DEBUG');
        $callback = json_decode($callback,true);

        if($callback['status'] == 2){
            $this->success('修改成功',U('Order/syncedit_order',array('order_id'=>$data['order_id'],'tag'=>$tag)));
            exit;
        }

        $this->initEditor(); // 编辑器
        $this->assign('tag',$tag);
        $this->assign('order',$callback['data']['order']);
        $this->assign('province',$callback['data']['province']);
        $this->assign('city',$callback['data']['city']);
        $this->assign('area',$callback['data']['area']);
        $this->assign('orderGoods',$callback['data']['orderGoods']);
        $this->assign('shipping_list',$callback['data']['shipping_list']);
        $this->assign('payment_list',$callback['data']['payment_list']);
        $this->display();
    }
    /*
    *订单维修首页
    */
    public function fix_list(){
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['tuihuo_time'] = array('between',"$begin,$end");
        }

        I('status')!="" ? $condition['status'] = I('status') : false;
        I('type')!="" ? $condition['type'] = I('type') : false;
        I('order_sn') && $condition['_string'] = ' (a.order_sn like "%'.I('order_sn').'%")  OR (a.remark like "%'.I('order_sn').'%") ';
        I('consignee') && $condition['_string'] = ' (b.nickname like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") ';
        $condition['a.store_id']=STORE_ID;

        $count = M('fix_goods a')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->where($condition)->count();
        $Page  = new Page($count,20);
        //  搜索条件下 分页赋值

        $show = $Page->show();
        //获取订单列表
        $orderList = M('fix_goods a')
            ->field('a.*,b.*,c.original_img as imgs,c.goods_name,d.key_name')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->join('ty_spec_goods_price d ON a.spec_key=d.key','LEFT')
            ->where($condition)->limit("$Page->firstRow,$Page->listRows")
            ->order('a.id desc')
            ->select();

        foreach ($orderList as &$item){
            $item['fix_sn'] = M('order')->where(['fix_id'=>$item['id']])->getField('order_sn');
        }
        // dump($orderList);
        $this->assign('orderList',$orderList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    /*
   *订单完成维修
   */
    public function fix_finish()
    {
        $id = I('id');
        $fix_order = M('order')->where(['fix_id'=>$id])->find();
        if($fix_order){
            exit(json_encode([
                'code'=>'300',
                'msg'=>'操作失败'
            ]));
        }

        try {
            M()->startTrans();
            $order_id = I('order_id');
            $price = I('price');
            $fix = M('fix_goods')->where(['id'=>$id])->find();
            $order = M('order')->where(['order_id'=>$order_id])->find();
            $data['order_sn'] = $this->get_order_sn();
            $data['master_order_sn'] = '';
            $data['user_id'] = $order['user_id'];
            $data['store_id'] = $order['store_id'];
            $data['ufenbu_id'] = $order['ufenbu_id'];
            $data['consignee'] = $order['consignee'];
            $data['address'] = $order['address'];
            $data['mobile'] = $order['mobile'];
            $data['goods_price'] = $price;
            $data['order_amount'] = $price;
            $data['total_amount'] = $price;
            $data['add_time'] = time();
            $data['fix_id'] = $id;
            // dump($data);
            $orderId = M('order')->add($data);
            $goods = M('goods')->where(['goods_id'=>$fix['goods_id']])->find();
            // $spec = M('spec_goods_price')->where(['key'=>$fix['spec_key'],'goods_id'=>$fix['goods_id'],'order_id'=>$order_id])->find();
            $spec = M('order_goods')->where(['key'=>$fix['spec_key'],'goods_id'=>$fix['goods_id'],'order_id'=>$order_id])->find();
            $goodsData['order_id'] = $orderId;
            $goodsData['goods_id'] = $fix['goods_id'];
            $goodsData['goods_name'] = $goods['goods_name'];
            $goodsData['goods_sn'] = $goods['goods_sn'];
            $goodsData['goods_num'] = 1; //固定都是1个数量
            $goodsData['market_price'] = $price;
            $goodsData['goods_price'] = $price;
            $goodsData['member_goods_price'] = $price;
            $goodsData['spec_key'] = $fix['spec_key'];
            $goodsData['spec_key_name'] = $spec['spec_key_name'];
            $goodsData['sku'] = $spec['sku'];
            $goodsData['store_id'] = $order['store_id'];
            $goodsData['points'] = $goods['points'];
            $goodsData['floating'] = 100;
            M('order_goods')->add($goodsData);
            M('fix_goods')->where(['id'=>$id])->save(['status'=>1,'status_time'=>date('Y-m-d H:i:s',time())]);
            M()->commit();
            exit(json_encode([
                'code'=>'200',
                'msg'=>'修理完成，系统自动创建销量单成功！'
            ]));
        }catch (Exception $e){
            Log::record($e->getMessage(),'ERR');
            M()->rollback();
            exit(json_encode([
                'code'=>'300',
                'msg'=>'操作失败'
            ]));
        }


    }


    /*
    *导出维修单
    */
    public function export_fix(){

        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['addtime'] = array('between',"$begin,$end");
        }

        I('status')!="" ? $condition['status'] = I('status') : false;
        I('b1')!="" ? $condition['b.b1'] = I('b1') : false;
        I('type')!="" ? $condition['type'] = I('type') : false;
        //I('order_sn') ? $condition['remark'] = array('like','%'.trim(I('order_sn')).'%') : false;
        I('order_sn') && $condition['_string'] = ' (remark like "%'.I('order_sn').'%")  OR (order_sn like "%'.I('order_sn').'%") ';
        I('consignee') && $condition['_string'] = ' (nickname like "%'.I('consignee').'%")  OR (company like "%'.I('consignee').'%") OR (store_name like "%'.I('consignee').'%") ';
        $condition['a.store_id']=STORE_ID;

        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号/备注</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">买家</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">单价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">创建时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">类型</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">完成时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">关联单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">领取状态</td>';
        $strTable .= '</tr>';

        $orderList = M('fix_goods a')
            ->field('a.*,(a.member_goods_price),b.*,c.goods_name,CONCAT(b.b1,b.b2,b.b3,if(b.fast_flag="1","快","")) as bianshi_xian,e.key_name')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->join('ty_spec_goods_price e ON a.spec_key = e.key','LEFT')
            ->where($condition)->order('a.id desc')->select();
        foreach ($orderList as &$item){
            $item['fix_sn'] = M('order')->where(['fix_id'=>$item['id']])->getField('order_sn');
            $item['receive'] = $item['is_receive'] ? '已领取' : '未领取';
            $item['status_str'] = $item['status'] ? '已完成' : '未完成';
            $item['type_str'] = $item['type'] ? '维修' : '换货';
            $item['status_time'] = $item['status_time']??'未完成';

            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$item['order_sn'].'/'.$item['remark'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$item['company'].'('.$item['bianshi_xian'].')</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['goods_name'].'【'.$item['key_name'].'】</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['member_goods_price'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['goods_num'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$item['addtime']).'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['type_str'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['status_str'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['status_time'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['fix_sn'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['receive'].' </td>';
            $strTable .= '</tr>';
        }

        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'联鑫壹天达维修换货单');
        exit();

    }

    /**
     * 获取商品信息
     */
    public function ajax_order_goods(){
//        $where = ' is_on_sale = 1 and is_delete=0 and goods_state=1 and store_id ='.STORE_ID.' ';//搜索条件
        $condition = [];
        if(I('keywords')){
            $keywords = I('keywords');
            $condition['_complex'] = [
                'g.goods_name' => ['like', '%'.$keywords.'%'],
                's.key_name' => ['like', '%'.$keywords.'%'],
                '_logic' => 'OR'
            ];
        }
        $where = [
            'g.is_on_sale' => 1,
            'g.is_delete' => 0,
            'g.goods_state' => 1,
            'g.store_id' => STORE_ID,
        ];
        $count = M('goods g')
            ->field('g.*,s.key_name,s.key')
            ->join('ty_spec_goods_price s ON g.goods_id = s.goods_id')
            ->where($where)
            ->where($condition)
            ->count();

        $Page  = new AjaxPage($count,20);
//        foreach($condition as $key=>$val) {
//            $Page->parameter[$key] = urlencode($val);
//        }
        $show = $Page->show();
        $goodsList = M('goods g')
            ->field('g.*,s.key_name,s.key,s.price')
            ->join('ty_spec_goods_price s ON g.goods_id = s.goods_id')
            ->where($where)
            ->where($condition)
            ->order('g.goods_id DESC')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();

//        dump($goodsList);exit;
        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);
        $this->display();
    }

    /**
     * 构建选择商品表单
     * */
    public function ajax_order_goods_table()
    {
        $goods_ids = I('goods_ids');
        if (empty($goods_ids))
            exit(json_encode(['status'=>-1,'msg'=>'goods_ids不能为空']));

        $where = [
            's.key' => [
                'in',
                $goods_ids
            ]
        ];
        $goodsList = M('goods g')
            ->field('g.*,s.key_name,s.key,s.price')
            ->join('ty_spec_goods_price s ON g.goods_id = s.goods_id')
            ->where($where)
            ->select();
//        dump($goodsList);exit;
        $this->assign('goodsList',$goodsList);
        $this->display();
    }
    public function driver_list()
    {

        $order_sn= I('order_sn');
        $pay_status= I('pay_status');
        $driver_status= I('driver_status');
        $create_date = I('create_date');
        $create_date = str_replace("+"," ",$create_date);
        $create_date2 = $create_date  ? $create_date  : date('Y-m-d',strtotime('-1 month')).' 00:00 - '.date('Y-m-d',strtotime('+1 month')).' 23:59';
        $create_date3 = explode(' - ',$create_date2);
        $create_date4=($create_date3[0]==$create_date3[1]) ? strtotime($create_date3[1])+86399 :strtotime($create_date3[1]);
        $where = " a.order_status in (1,2) and a.store_id = ".STORE_ID." and a.ruku_last_time >= '".strtotime($create_date3[0])."' and a.ruku_last_time <= '".$create_date4."' ";

        if($order_sn){
            $where .= " and a.order_sn like '%".$order_sn."%'";
        }

        if($driver_status){
            switch ($driver_status){
                case 2:
                    $where .= " and a.driver_time IS NOT NULL ";
                    break;
                case 1:
                    $where .= " and a.driver_time IS NULL ";
                    break;
            }
        }



        if($pay_status){
            switch ($pay_status){
                case 2:
                    $where .= " and a.pay_status = 1";
                    break;
                case 1:
                    $where .= " and a.pay_status = 0";
                    break;
            }
        }



        // dump($where);
        $count = M()->query("SELECT a.order_id,a.order_sn,a.order_amount,a.coupon_price,a.total_amount from ty_order a where $where ");

        //计算合计金额
        $heji=0;
        foreach($count as $v){
            $heji+=$v['total_amount'];
        }
        $Page  = new Page(count($count),20);
        if (I('type') == 'export'){
            $list = M()->query("SELECT a.order_id,a.order_sn,a.order_amount,a.coupon_price,a.ruku_last_time,a.driver_time,a.pay_status,a.pay_time,b.company,a.ruku_last_time,a.total_amount from ty_order a 
			left join ty_users b on a.user_id=b.user_id
		 where $where  ORDER BY a.ruku_last_time asc ");
        }else {
            $list = M()->query("SELECT a.order_id,a.order_sn,a.order_amount,a.coupon_price,a.ruku_last_time,a.driver_time,a.pay_status,a.pay_time,b.company,a.ruku_last_time,a.total_amount from ty_order a 
			left join ty_users b on a.user_id=b.user_id
		 where $where  ORDER BY a.ruku_last_time asc limit $Page->firstRow,$Page->listRows");
        }



        // dump($where);
        foreach($list as $key=>$v){
            $list[$key]['order_amount'] = $v['total_amount'];
            $list[$key]['driver_time']= $v['driver_time'] ? date('Y-m-d H:i:s',$v['driver_time']) : '';
            $list[$key]['driver_status']= $v['driver_time'] ? '已送达' : '未送达';
            $list[$key]['ruku_last_time']= date('Y-m-d H:i:s',$v['ruku_last_time']);
            $list[$key]['pay_status']= $v['pay_status'] ? '已支付' : '未支付';
            $list[$key]['pay_time']= !$v['pay_time'] && $v['pay_status'] ? '财务已对账' : '';

        }
        // dump($list);
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();
        $this->assign([
            'heji'=>$heji,
        ]);
// 		dump($order_status);
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);

        if (I('type') == 'export'){
            $export = $this->fetch('driver_list_export');
            downloadExcel($export,'订单配送记录');
        }
        $this->display();
    }
    /**
     *导出活动产品
     */
    public function export_prom_goods(){
        $prom_id = I('prom_id');

        $prom = M('prom_goods')->where(['id'=>$prom_id])->find();

        $goods_id = 0;
        if(!empty($prom['goods_key'])){
            $goods_id = json_decode($prom['goods_key'],true);
        }

        $order_list = M('order_goods g')
            ->join('ty_order o on o.order_id = g.order_id','left')
            ->join('ty_users u on u.user_id = o.user_id','left')
            ->where(['g.prom_id'=>$prom_id,'g.spec_key'=>['in',implode(',',$goods_id)]])
            ->select();

        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">买家</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">单价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">下单时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">订单状态</td>';
        $strTable .= '</tr>';

        $order_status = C('ORDER_STATUS');
        foreach ($order_list as &$item){
            $status_msg =

            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$item['order_sn'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$item['company'].'('.$item['biaoshi_xian'].')</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['goods_name'].'【'.$item['spec_key_name'].'】</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['member_goods_price'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$item['goods_num'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$item['add_time']).'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$order_status[$item['order_status']].' </td>';
            $strTable .= '</tr>';
        }

        $strTable .='</table>';
        unset($orderList);
        downloadExcel($strTable,'活动订单');
        exit();
    }
}
